英文:
Go binary.Read into slice of data gives zero result
问题
我想要读写二进制数据到文件,我的数据只是一个切片。编码部分是正常工作的,但是通过binary.Read
解码时得到的结果是零。我做错了什么?
data := []int16{1, 2, 3}
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.LittleEndian, data)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Println(buf.Bytes())
// 在这一步之前都是正常工作的
r := bytes.NewReader(buf.Bytes())
got := []int16{}
if err := binary.Read(r, binary.LittleEndian, &got); err != nil {
fmt.Println("binary.Read failed:")
}
fmt.Println("got:", got)
运行这段代码得到的结果是:
[1 0 2 0 3 0]
got: []
Playground链接在这里:
https://go.dev/play/p/yZOkwXj8BNv
英文:
I want to read and write binary data to file and my data is simply slice. The encoding part is working, but my decoding via binary.Read
gives zero result. What did I do wrong?
data := []int16{1, 2, 3}
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.LittleEndian, data)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Println(buf.Bytes())
// working up to this point
r := bytes.NewReader(buf.Bytes())
got := []int16{}
if err := binary.Read(r, binary.LittleEndian, &got); err != nil {
fmt.Println("binary.Read failed:")
}
fmt.Println("got:", got)
Running this code gives
[1 0 2 0 3 0]
got: []
The playground link is here:
https://go.dev/play/p/yZOkwXj8BNv
答案1
得分: 2
你必须将切片的大小设置为你想从缓冲区中读取的大小。你得到了一个空的结果,因为got
的长度为零。
got := make([]int16, buf.Len()/2)
if err := binary.Read(buf, binary.LittleEndian, &got); err != nil {
fmt.Println("binary.Read failed:")
}
正如JimB所说,你可以直接从缓冲区中读取。
另请参阅binary.Read
的文档。
Read
从r
中读取结构化的二进制数据到data
中。data
必须是一个指向固定大小值或固定大小值切片的指针。从r
中读取的字节使用指定的字节顺序解码,并写入到data
的连续字段中。[...]
英文:
You have to make your slice as large as you want to read from your buffer. You got an empty result because got has a length of zero.
got := make([]int16, buf.Len()/2)
if err := binary.Read(buf, binary.LittleEndian, &got); err != nil {
fmt.Println("binary.Read failed:")
}
And as JimB stated, you can read directly from your buffer.
See also the documentation of binary.Read
> Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data. [...]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论