Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go binary.Read into slice of data gives zero result

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading