如果我已有[]byte
,建议将一个或多个uint32
值的字节附加到该字节的方法是什么?
例如,我应该将// ???
替换为:
s := []byte{0x00, 0x01, 0x02, 0x03}
u := uint32(0x07060504)
// ???
fmt.Println(s) // Should print [0 1 2 3 4 5 6 7]
编辑:一个选项是
s = append(s, byte(u)); s = append(s, byte(u >> 8)); s = append(s, byte(u >> 16)); s = append(s, byte(u >> 24))
,但是有没有更惯用的方法呢?也许使用package binary和/或package bytes?
最佳答案
一种选择是按照问题的建议附加单个字节。多个append
调用可以合并为一个调用:
s = append(s, byte(u), byte(u>>8), byte(u>>16), byte(u>>24))
二进制包也可以用作问题提示:
var b [4]byte
binary.LittleEndian.PutUint32(b[:], u)
s = append(s, b[:]...)
Run it on the Go playground。
最后一个片段应在堆栈上分配
b
。如果没有,那么可以使用以下代码避免额外的堆分配:s = append(s, " "...) // append four bytes (the values don't matter)
binary.LittleEndian.PutUint32(s[len(s)-4:], u) // overwrite those bytes with the uint32
关于go - 将uint32的字节附加到 byte slice 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764140/