基于字节段解析文件

huangapple go评论81阅读模式
英文:

Parsing a file based on byte sections

问题

我正在解析一个文件,该文件逐字节读取,并且我有关于每个字节表示文件的哪个部分的指令。

文件的顺序如下:

  1. 前4个字节是版本号。

  2. 接下来的4个字节是一个整数,表示预期的订单数量。

  3. 对于每个订单(从第2步开始),4个字节的整数是订单ID。

所以为了解析这个文件,我首先加载文件:

file, err := os.Open("orders.abc")

version := make([]byte, 4)
c, err := file.Read(version)
fmt.Printf("读取 %d 个字节,版本号是 %d", c, version)

orderCount := make([]byte, 4)
c2, err := file.Read(orderCount)
fmt.Printf("读取 %d 个字节,订单数量是 %d", c2, orderCount)

for i := 0; i < orderCount_as_int; i++ {

  orderId := make([]byte, 4)
  c3, err := file.Read(orderId)     
}

有没有更优雅的方法来解析这样的文件?

另外,我如何将版本号和订单数量转换为整数,以便我可以使用这个值?

英文:

I am parsing a file, the file is read byte by byte and I have instructions on which byte represents what part of the file.

Orders file:

  1. first 4 bytes is the version

  2. next 4 bytes is an integer, representing how many orders to expect.

  3. for each order (from #2), 4 bytes integer is the order ID.

So to parse this, I first load the file:

file, err := os.Open(&quot;orders.abc&quot;)

version := make([]byte, 4)
c, err := file.Read(version)
fmt.Printf(&quot;read %d, version is %d&quot;, c, version)

orderCount := make([]byte, 4)
c2, err := file.Read(orderCount)
fmt.Printf(&quot;read %d, orderCount is %d&quot;, c2, orderCount)

for i := 0; i &lt; orderCount_as_int; i++ {

  orderId := make([]byte, 4)
  c3, err := file.Read(orderId)     
}

Is there a more elegant way to be parsing a file like this?

Also, how can I convert the version/orderCount into an integer so I can use the value?

答案1

得分: 2

你想要使用encoding/binary.Read而不是直接调用Read方法。例如:

var version int32
err := binary.Read(file, binary.LittleEndian, &version)

(你还需要确定文件中的数据是大端序还是小端序,并选择适当的字节顺序)。binary包会为你进行解码。

英文:

You want to use encoding/binary.Read rather than calling Read directly. e.g.

var version int32
err := binary.Read(file, binary.LittleEndian, &amp;version)

(also you need to know whether your data is in the file as big-endian or little-endian and choose the appropriate ByteOrder). The binary package will do the decoding for you.

huangapple
  • 本文由 发表于 2023年2月23日 23:49:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定