猿问

如何迭代两个字节切片

每个字节切片代表一个键,我想从下键迭代到上键 pkg https://golang.org/pkg/bytes/


假设有两个字节片 lower :=[]byte upper :=[]byte ,我该怎么做?


   for i:=lower;i<upper;i++ {


    }

例子


 lower:= []byte{0,0,0,0,0,0}  // can be thought as 0 in decimal

 upper:= []byte{0,0,0,0,0,255} // can be thought as 255 in decimal

 //iterate over all numbers in between lower and upper

// {0,0,0,0,0,0} {0,0,0,0,0,1} ... {0,0,0,0,0,2} ..{0,0,0,0,0,255}

 for i:=0; i<=255;i++{


 }

//instead of converting to decimal iterate using byte arrays

或者,如何将字节数组(上下)的范围划分为更小的范围


\\eg 

   l := []byte{0,1}

   r := []byte{1,255}

把它分成更小的范围


   l := []byte{0 , 1}

   l2:= []byte{x1,y1}

... 

   r:= []byte{1,255}


潇湘沐
浏览 210回答 1
1回答

慕斯王

最简单的方法是将字节简单地解释为大端整数。由于 Go 中没有 int48 类型(即六字节大整数),因此您必须首先使用前导零扩展字节切片,直到它适合下一个最大类型 int64 或 uint64。然后与标准 for 循环交互,并为每次迭代反转解码:package mainimport (&nbsp; &nbsp; &nbsp; &nbsp; "encoding/binary"&nbsp; &nbsp; &nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; &nbsp; &nbsp; lower := []byte{0, 0, 0, 0, 0, 0}&nbsp; &nbsp; &nbsp; &nbsp; lowerInt := binary.BigEndian.Uint64(append([]byte{0, 0}, lower...))&nbsp; &nbsp; &nbsp; &nbsp; upper := []byte{0, 0, 0, 0, 0, 255}&nbsp; &nbsp; &nbsp; &nbsp; upperInt := binary.BigEndian.Uint64(append([]byte{0, 0}, upper...))&nbsp; &nbsp; &nbsp; &nbsp; buf := make([]byte, 8)&nbsp; &nbsp; &nbsp; &nbsp; for i := lowerInt; i <= upperInt; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; binary.BigEndian.PutUint64(buf, i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(buf[2:])&nbsp; &nbsp; &nbsp; &nbsp; }}// Output:// [0 0 0 0 0 0]// [0 0 0 0 0 1]// ...// [0 0 0 0 0 254]// [0 0 0 0 0 255]在操场上尝试:https: //play.golang.org/p/86iN0V47nZi
随时随地看视频慕课网APP

相关分类

Go
我要回答