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

golang parsing []bytes to []int32 returns blank

I am trying to parse a []bytes into []int32; but I am getting a blank reply, see this go playground.

code:

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

func main() {
    someBytes := []byte{0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
    someInts := make([]int32, 0)
    r := bytes.NewReader(someBytes)
    if err := binary.Read(r, binary.LittleEndian, &someInts); err != nil {
        fmt.Println("binary.Read failed:", err)
    }

    fmt.Printf("%v \n", someBytes)
    fmt.Println(someInts)
}

Unless I am misreading the docs:

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

Data must be a pointer to a fixed-size value or a slice of fixed-size values

Which it is.

I am expecting to receive: [9 0 0 0]. Does anyone know why?

>Solution :

You created a slice with 0 length, the slice contains zero int32 values. So nothing is decoded.

Create a slice with 4 elements, so 4 elements will be decoded:

someInts := make([]int32, 4)

With this change output will be (try it on the Go Playground):

[9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 
[9 0 0 0]
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