英文:
Writing into fixed size Buffers in Golang with offsets
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对Golang还不熟悉,我正在尝试写入一个缓冲区,在开始写入之前,该缓冲区应该填充为特定大小的0。
我的尝试:
buf := bytes.NewBuffer(make([]byte, 52))
var pktInfo uint16 = 243
var pktSize uint16 = 52
var pktLine uint16 = binary.LittleEndian.Uint16(data)
var pktId uint16 = binary.LittleEndian.Uint16(data[6:])
// 头部
binary.Write(buf, binary.LittleEndian, pktInfo)
binary.Write(buf, binary.LittleEndian, pktSize)
binary.Write(buf, binary.LittleEndian, pktLine)
// 主体
binary.Write(buf, binary.LittleEndian, pktId)
(...更多代码)
fmt.Printf("%x\n", data)
fmt.Printf("%x\n", buf.Bytes())
问题是它在字节之后进行写入,而不是从开头开始写入。我该如何解决这个问题?
英文:
I'm new to Golang and I'm trying to write into a Buffer that should be 0 filled to a specific size before starting writing into it.
My try:
buf := bytes.NewBuffer(make([]byte, 52))
var pktInfo uint16 = 243
var pktSize uint16 = 52
var pktLine uint16 = binary.LittleEndian.Uint16(data)
var pktId uint16 = binary.LittleEndian.Uint16(data[6:])
// header
binary.Write(buf, binary.LittleEndian, pktInfo)
binary.Write(buf, binary.LittleEndian, pktSize)
binary.Write(buf, binary.LittleEndian, pktLine)
// body
binary.Write(buf, binary.LittleEndian, pktId)
(...a lot more)
fmt.Printf("%x\n", data)
fmt.Printf("%x\n", buf.Bytes())
Problem is it writes after the bytes instead of writing from the start. How do I do that?
答案1
得分: 9
你不需要重新分配bytes.Buffer
的切片,或者如果你确实需要重新分配,你需要设置容量而不是长度:
buf := bytes.NewBuffer(make([]byte, 0, 52)) // 或者简单地
buf := bytes.NewBuffer(nil)
还有buf.Reset()
,但对于这个特定的示例来说,这有点过度。
切片:size参数指定长度。切片的容量等于其长度。可以提供第二个整数参数来指定不同的容量;它必须不小于长度,所以
make([]int, 0, 10)
分配了一个长度为0、容量为10的切片。
英文:
You don't need to reallocate the slice for bytes.Buffer
, or if you do, you need to set the cap not the len:
buf := bytes.NewBuffer(make([]byte, 0, 52)) // or simply
buf := bytes.NewBuffer(nil)
There's also buf.Reset()
but that's an overkill for that specific example.
> Slice: The size specifies the length. The capacity of the slice is
equal to its length. A second integer argument may be provided to
specify a different capacity; it must be no smaller than the
length, so make([]int, 0, 10) allocates a slice of length 0 and
capacity 10.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论