简体   繁体   English

在 () golang 中读取二进制数据

[英]Reading Binary Data in () golang

I need to read a specific binary data format ( https://www.usna.edu/Users/oceano/pguth/md_help/html/BT_file_format.htm ).我需要读取特定的二进制数据格式( https://www.usna.edu/Users/oceano/pguth/md_help/html/BT_file_format.htm )。 Go seems to be able to do so quite nicely: Go 似乎能够很好地做到这一点:

// ...

    f, _ := os.Open(filename)
    var data struct {
        Indicator         [10]byte
        Columns           [4]byte
        Rows              [4]byte
        DataSize          [4]byte
        UTMFlag           [2]byte
        UTMZone           [2]byte
        LeftExtend        [4]byte
        RightExtend       [4]byte
        BottomExtend      [4]byte
        TopExtend         [4]byte
        FloatingPointFlag [2]byte
    }
    _ = binary.Read(f, binary.LittleEndian, &data)
// ...

That seems to work since spew.dump(data.Indicator) for example return the correct data.这似乎有效,因为spew.dump(data.Indicator)例如返回正确的数据。 What I do not understand is how to cast fixed slices like [2]byte to an integer I can actually work with.我不明白的是如何将像[2]byte这样的固定切片转换为我可以实际使用的 integer。 Any suggestions?有什么建议么?

Declare the fields with fixed size numeric types:声明具有固定大小数字类型的字段:

var data struct {
    Indicator         [10]byte
    Columns           uint32
    Rows              uint32
    DataSize          uint32
    UTMFlag           uint16
    UTMZone           uint16
    LeftExtend        uint32
    RightExtend       uint32
    BottomExtend      uint32
    TopExtend         uint32
    FloatingPointFlag uint16
}

I used unsigned integers here, but it's also OK to use signed integers.我在这里使用了无符号整数,但也可以使用有符号整数。 Use the type that matches the data.使用与数据匹配的类型。

https://play.golang.org/p/95yqMAYsWVR https://play.golang.org/p/95yqMAYsWVR

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

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