为了账号安全,请及时绑定邮箱和手机立即绑定

如何迭代两个字节切片

如何迭代两个字节切片

Go
潇湘沐 2022-06-13 14:59:28
每个字节切片代表一个键,我想从下键迭代到上键 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}
查看完整描述

1 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

最简单的方法是将字节简单地解释为大端整数。由于 Go 中没有 int48 类型(即六字节大整数),因此您必须首先使用前导零扩展字节切片,直到它适合下一个最大类型 int64 或 uint64。然后与标准 for 循环交互,并为每次迭代反转解码:


package main


import (

        "encoding/binary"

        "fmt"

)


func main() {

        lower := []byte{0, 0, 0, 0, 0, 0}

        lowerInt := binary.BigEndian.Uint64(append([]byte{0, 0}, lower...))


        upper := []byte{0, 0, 0, 0, 0, 255}

        upperInt := binary.BigEndian.Uint64(append([]byte{0, 0}, upper...))


        buf := make([]byte, 8)

        for i := lowerInt; i <= upperInt; i++ {

                binary.BigEndian.PutUint64(buf, i)

                fmt.Println(buf[2:])

        }

}

// 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


查看完整回答
反对 回复 2022-06-13
  • 1 回答
  • 0 关注
  • 209 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号