Home > Mobile >  Go binary.Read into slice of data gives zero result
Go binary.Read into slice of data gives zero result

Time:04-30

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

CodePudding user response:

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. [...]

  • Related