golang parsing []bytes to []int32 returns blank

Advertisements

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:

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]

Leave a ReplyCancel reply