亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何迭代兩個字節切片

如何迭代兩個字節切片

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 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號