mardi 29 mars 2022

How to read a binary file into a struct and reflection - Go Language

I am trying to write a program to read a binary file into a struct in golang, the approach is to use the binary package to read a binary file to populate a struct that contains arrays, I am using arrays and not slices because I want to specify the field length, this seems to work fine but when I try to use reflection to print our the values of the fields I am getting this error

panic: reflect: call of reflect.Value.Bytes on array Value

Here is the code

package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "os"
    "reflect"
)

type SomeStruct struct {
    Field1                     [4]byte
    Field2                  [2]byte
    Field3                [1]byte

}

func main() {
    f, err := os.Open("/Users/user/Downloads/file.bin")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    s := SomeStruct{}
    err = binary.Read(f, binary.LittleEndian, &s)

    numOfFields := reflect.TypeOf(s).NumField()
    ps := reflect.ValueOf(&s).Elem()

    for i := 0; i < numOfFields; i++ {
        value := ps.Field(i).Bytes()
        for j := 0; j < len(value); j++ {
            fmt.Print(value[j])
        }
    }
}

when I change the code to this

package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "os"
    "reflect"
)

type SomeStruct struct {
    Field1 [4]byte
    Field2 [2]byte
    Field3 [1]byte
}

func main() {
    f, err := os.Open("/Users/user/Downloads/file.bin")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    s := SomeStruct{}
    err = binary.Read(f, binary.LittleEndian, &s)

    numOfFields := reflect.TypeOf(s).NumField()
    ps := reflect.ValueOf(&s).Elem()

    for i := 0; i < numOfFields; i++ {
        value := ps.Field(i)
        fmt.Print(value)

    }
}


it prints the arrays with their ascii representation, I need to print the char representation of the ascii and that when I get the panic

thoughts?





Aucun commentaire:

Enregistrer un commentaire