循环将在 golang 中按 1 到 5 [] 字节的顺序输出

如何制作一个按 1 到 5 [] 字节顺序输出的循环?


这是我在输出中需要的:


[0]

[1]

[2]

...

[255]

[0 1]

[1 1]

[2 1]

...

etc (to max 5 bytes)

例如,如果我从数字进行正常循环并使用这些函数将它们转换为字节:


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

    b : intToBytes(i)

    fmt.Println(b)

}


func intToBytes(val int) []byte {

    r := make([]byte, 5)

    for i := int(0); i < 5; i++ {

        r[i] = byte((val >> (8 * i)) & 0xff)

    }

    return r

}

输出末尾会有额外的零。


如果这个选项是正确的,那么如何去掉多余的零?


杨魅力
浏览 85回答 1
1回答

千巷猫影

这是一个解决方案。使用 append 更新字节切片长度。当移位结果为零时停止。package mainimport "fmt"func intToBytes(val int) []byte {&nbsp; &nbsp; b := make([]byte, 0, 5)&nbsp; &nbsp; for i := range b[:cap(b)] {&nbsp; &nbsp; &nbsp; &nbsp; v := val >> (8 * i)&nbsp; &nbsp; &nbsp; &nbsp; if v == 0 && i != 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; b = append(b, byte(v))&nbsp; &nbsp; }&nbsp; &nbsp; return b}func main() {&nbsp; &nbsp; for i := 0; i < 4; i++ {&nbsp; &nbsp; &nbsp; &nbsp; b := intToBytes(i)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(b)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("...")&nbsp; &nbsp; for i := 260 - 8; i < 260; i++ {&nbsp; &nbsp; &nbsp; &nbsp; b := intToBytes(i)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(b)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("...")&nbsp; &nbsp; for i := 8589934590 - 4; i < 8589934590; i++ {&nbsp; &nbsp; &nbsp; &nbsp; b := intToBytes(i)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(b)&nbsp; &nbsp; }}https://go.dev/play/p/b91oYBpOw_Y[0][1][2][3]...[252][253][254][255][0 1][1 1][2 1][3 1]...[250 255 255 255 1][251 255 255 255 1][252 255 255 255 1][253 255 255 255 1]
打开App,查看更多内容
随时随地看视频慕课网APP