英文:
Parsing a file based on byte sections
问题
我正在解析一个文件,该文件逐字节读取,并且我有关于每个字节表示文件的哪个部分的指令。
文件的顺序如下:
-
前4个字节是版本号。
-
接下来的4个字节是一个整数,表示预期的订单数量。
-
对于每个订单(从第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:
-
first 4 bytes is the version
-
next 4 bytes is an integer, representing how many orders to expect.
-
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("orders.abc")
version := make([]byte, 4)
c, err := file.Read(version)
fmt.Printf("read %d, version is %d", c, version)
orderCount := make([]byte, 4)
c2, err := file.Read(orderCount)
fmt.Printf("read %d, orderCount is %d", c2, orderCount)
for i := 0; i < 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, &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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论