go - 将uint32的字节附加到 byte slice 吗?

标签 go binary byte slice endianness

如果我已有[]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/

相关文章:

c - 这个 reverseBytes 方法是如何工作的?

github - 通过 Travis-CI 在 Go 中作为版本的 Git 标签名称

c - 两个二进制数异或的问题

function - range 函数和 range 关键字有什么区别?

image - 将二进制值转换为十进制矩阵

delphi - Delphi 有时会将文本表单文件 (DFM) 恢复为二进制格式吗?

go - 无法在Golang中将字节转换为int

python - PIL : Convert Bytearray to Image

json - 如何读取json格式的数据?

go - 将 google-apis 用于 google 表格,如何根据条件更新特定单元格