如何在Go中读取打包的二进制数据?

Chr*_*end 6 binaryfiles go

我试图找出在Python中生成的包装二进制文件的最佳方法,如下所示:

import struct
f = open('tst.bin', 'wb')
fmt = 'iih' #please note this is packed binary: 4byte int, 4byte int, 2byte int
f.write(struct.pack(fmt,4, 185765, 1020))
f.write(struct.pack(fmt,4, 185765, 1022))
f.close()
Run Code Online (Sandbox Code Playgroud)

我一直在修补我在Github.com和其他一些消息来源上看到的一些例子 但我似乎无法正常工作(更新显示工作方法). 在Go中做这种事的惯用方法是什么?这是几次尝试之一

更新和工作

package main

    import (
            "fmt"
            "os"
            "encoding/binary"
            "io"
            )

    func main() {
            fp, err := os.Open("tst.bin")

            if err != nil {
                    panic(err)
            }

            defer fp.Close()

            lineBuf := make([]byte, 10) //4 byte int, 4 byte int, 2 byte int per line

            for true {
                _, err := fp.Read(lineBuf)

                if err == io.EOF{
                    break
                }

                aVal := int32(binary.LittleEndian.Uint32(lineBuf[0:4])) // same as: int32(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
                bVal := int32(binary.LittleEndian.Uint32(lineBuf[4:8]))
                cVal := int16(binary.LittleEndian.Uint16(lineBuf[8:10])) //same as: int16(uint32(b[0]) | uint32(b[1])<<8)
                fmt.Println(aVal, bVal, cVal)
            }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*erg 5

Google 的“Protocol Buffers”是一种可移植性良好且相当简单的解决问题的方法。虽然现在已经太晚了,因为你已经开始工作了,但我花了一些精力来解释和编码它,所以无论如何我都会发布它。

您可以在https://github.com/mwmahlberg/ProtoBufDemo上找到代码

您需要使用您首选的方法(pip、操作系统包管理、源代码)安装 python 和Go的协议缓冲区

文件.proto

对于我们的示例来说,该.proto文件相当简单。我叫它data.proto

syntax = "proto2";
package main;

message Demo {
  required uint32  A = 1;
  required uint32 B = 2;

  // A shortcomning: no 16 bit ints
  // We need to make this sure in the applications
  required uint32 C = 3;
}
Run Code Online (Sandbox Code Playgroud)

现在您需要调用protoc该文件并让它提供 Python 和 Go 的代码:

protoc --go_out=. --python_out=. data.proto
Run Code Online (Sandbox Code Playgroud)

它生成文件data_pb2.pydata.pb.go. 这些文件提供对协议缓冲区数据的特定于语言的访问。

使用github上的代码时,只需发出

go generate
Run Code Online (Sandbox Code Playgroud)

在源目录中。

Python 代码

import data_pb2

def main():

    # We create an instance of the message type "Demo"...
    data = data_pb2.Demo()

    # ...and fill it with data
    data.A = long(5)
    data.B = long(5)
    data.C = long(2015)


    print "* Python writing to file"
    f = open('tst.bin', 'wb')

    # Note that "data.SerializeToString()" counterintuitively
    # writes binary data
    f.write(data.SerializeToString())
    f.close()

    f = open('tst.bin', 'rb')
    read = data_pb2.Demo()
    read.ParseFromString(f.read())
    f.close()

    print "* Python reading from file"
    print "\tDemo.A: %d, Demo.B: %d, Demo.C: %d" %(read.A, read.B, read.C)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

protoc我们导入并使用生成的文件。这里没有太多魔法。

去文件

package main

//go:generate protoc --python_out=. data.proto
//go:generate protoc --go_out=. data.proto
import (
    "fmt"
    "os"

    "github.com/golang/protobuf/proto"
)

func main() {

    // Note that we do not handle any errors for the sake of brevity
    d := Demo{}
    f, _ := os.Open("tst.bin")
    fi, _ := f.Stat()

    // We create a buffer which is big enough to hold the entire message
    b := make([]byte,fi.Size())

    f.Read(b)

    proto.Unmarshal(b, &d)
    fmt.Println("* Go reading from file")

    // Note the explicit pointer dereference, as the fields are pointers to a pointers
    fmt.Printf("\tDemo.A: %d, Demo.B: %d, Demo.C: %d\n",*d.A,*d.B,*d.C)
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们不需要显式导入,因为 的包data.protomain

结果

生成所需的文件并编译源代码后,当您发出

$ python writer.py && ./ProtoBufDemo
Run Code Online (Sandbox Code Playgroud)

结果是

* Python writing to file
* Python reading from file
    Demo.A: 5, Demo.B: 5, Demo.C: 2015
* Go reading from file
    Demo.A: 5, Demo.B: 5, Demo.C: 2015
Run Code Online (Sandbox Code Playgroud)

请注意,存储库中的 Makefile 提供了用于生成代码、编译文件.go并运行这两个程序的快捷方式:

make run
Run Code Online (Sandbox Code Playgroud)


mjo*_*ois 4

Python 格式字符串为iih,表示两个 32 位有符号整数和一个 16 位有符号整数(请参阅文档)。您可以简单地使用第一个示例,但将结构更改为:

type binData struct {
    A int32
    B int32
    C int16
}

func main() {
        fp, err := os.Open("tst.bin")

        if err != nil {
                panic(err)
        }

        defer fp.Close()

        for {
            thing := binData{}
            err := binary.Read(fp, binary.LittleEndian, &thing)

            if err == io.EOF{
                break
            }

            fmt.Println(thing.A, thing.B, thing.C)
        }
}
Run Code Online (Sandbox Code Playgroud)

请注意,Python 打包没有明确指定字节序,但如果您确定运行它的系统生成了小字节序二进制文件,那么这应该可以工作。

编辑:添加main()功能来解释我的意思。

编辑 2:大写的结构字段,以便binary.Read可以写入其中。