英文:
loop that will output in order from 1 to 5 []bytes in golang
问题
如何创建一个循环,按顺序输出从1到5个字节的内容?
以下是我需要的输出:
[0]
[1]
[2]
...
[255]
[0 1]
[1 1]
[2 1]
...
等等(最多5个字节)
例如,如果我使用以下函数将数字转换为字节,并进行正常的循环:
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
}
输出的末尾会有额外的零。
如果要去除额外的零,可以尝试以下选项是否正确:
英文:
How to make a loop that will output in order from 1 to 5 []bytes?
Here is what I need in the output:
[0]
[1]
[2]
...
[255]
[0 1]
[1 1]
[2 1]
...
etc (to max 5 bytes)
For example, if I doing a normal loop from numbers and turn them into bytes using these functions:
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
}
there will be extra zeros at the end of the output.
If this option is correct, then how to get rid of extra zeros?
答案1
得分: 1
这是一个解决方案。使用append函数来更新字节切片的长度。当移位结果为零时停止。
package main
import "fmt"
func intToBytes(val int) []byte {
b := make([]byte, 0, 5)
for i := range b[:cap(b)] {
v := val >> (8 * i)
if v == 0 && i != 0 {
break
}
b = append(b, byte(v))
}
return b
}
func main() {
for i := 0; i < 4; i++ {
b := intToBytes(i)
fmt.Println(b)
}
fmt.Println("...")
for i := 260 - 8; i < 260; i++ {
b := intToBytes(i)
fmt.Println(b)
}
fmt.Println("...")
for i := 8589934590 - 4; i < 8589934590; i++ {
b := intToBytes(i)
fmt.Println(b)
}
}
[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]
你可以在这里查看代码的运行结果:链接
英文:
Here is a solution. Use append to update the byte slice length. Stop when the shifted result is zero.
package main
import "fmt"
func intToBytes(val int) []byte {
b := make([]byte, 0, 5)
for i := range b[:cap(b)] {
v := val >> (8 * i)
if v == 0 && i != 0 {
break
}
b = append(b, byte(v))
}
return b
}
func main() {
for i := 0; i < 4; i++ {
b := intToBytes(i)
fmt.Println(b)
}
fmt.Println("...")
for i := 260 - 8; i < 260; i++ {
b := intToBytes(i)
fmt.Println(b)
}
fmt.Println("...")
for i := 8589934590 - 4; i < 8589934590; i++ {
b := intToBytes(i)
fmt.Println(b)
}
}
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论