简体   繁体   English

如何将二进制文件读入结构和反射 - Go 语言

[英]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我正在尝试编写一个程序以将二进制文件读入 golang 中的结构,方法是使用二进制 package 读取二进制文件以填充包含 arrays 的结构,我使用的是 arrays 而不是切片,因为我想指定字段长度,这似乎工作正常但是当我尝试使用反射来打印我们的字段值时出现此错误

panic: reflect: call of reflect.Value.Bytes on array Value恐慌:反映:对数组值调用 reflect.Value.Bytes

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它打印 arrays 及其 ascii 表示,我需要打印 ascii 的 char 表示,当我感到恐慌时

thoughts?想法?

The Bytes documentation says:字节文档说:

Bytes returns v's underlying value.字节返回 v 的基础值。 It panics if v's underlying value is not a slice of bytes.如果 v 的基础值不是字节片段,它会发生恐慌。

Slice the array to get a slice of bytes:对数组进行切片以获得字节切片:

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

You can also iterate through the array:您还可以遍历数组:

value := ps.Field(i)
for j := 0; j < value.Len(); j++ {
    fmt.Print(byte(value.Index(j).Uint()))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM