用偏移量在Golang中写入固定大小的缓冲区 [英] Writing into fixed size Buffers in Golang with offsets
问题描述
我是Golang的新手,我正在尝试写入一个Buffer,在开始写入之前,它应该以0填充到特定大小.
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.
我的尝试:
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?
推荐答案
您不需要为 bytes.Buffer
重新分配切片,或者如果这样做,则需要设置上限镜头:
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)
还有 buf.Reset()
,但这对于该特定示例来说是一个过大的杀伤力.
There's also buf.Reset()
but that's an overkill for that specific example.
切片:大小指定长度.切片的容量为等于它的长度.可以提供第二个整数参数指定不同的容量;它必须不小于长度,因此make([] int,0,10)分配长度为0的切片,容量10.
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.
这篇关于用偏移量在Golang中写入固定大小的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!