Go二进制读取到数据切片中返回零结果。

huangapple go评论81阅读模式
英文:

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的文档。

Readr中读取结构化的二进制数据到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. [...]

huangapple
  • 本文由 发表于 2022年4月29日 20:11:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/72057783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定