Writing into fixed size Buffers in Golang with off

2019-08-09 03:44发布

问题:

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.



标签: go buffer