Writing into fixed size Buffers in Golang with offsets

若如初见. 提交于 2019-12-24 12:42:47

问题


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:


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.

make(slice, size, cap):

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.



来源:https://stackoverflow.com/questions/28639859/writing-into-fixed-size-buffers-in-golang-with-offsets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!