Skip to main content
 首页 » 编程设计

python之如何读取和解析二进制文件作为 Big Endian

2024年12月31日10artech

我有一个包含多种类型结构的二进制文件。 该文件包含 BIG Endian 格式的数据。

我正在尝试读取文件并打印文件中的记录总数。 (有多种类型的结构,每一种都有不同的大小)

这里是我的代码示例:

import os 
from ctypes import * 
 
class Header(Structure): 
    _fields_ = [("time", c_ushort), 
                ("typeA", c_ubyte, 4), 
                ("typeB", c_ubyte, 4), 
                ("size", c_ushort)] 
 
 
headerSize = sizeof(Header) 
 
file = open("D:\binaryFile.bin", "rb")  
numOfRecords = 0 
 
while 1: 
    # read the header 
   sizeToRead =  headerSize 
   data = file.read(sizeToRead) 
 
   # if we get to the end of the file 
   if not data: break 
 
   numOfRecords = numOfRecords + 1 
 
   # cast the data into Header structre 
   headerInstance = cast(data, POINTER(Header)).contents 
 
   # print the msg size (msg size = header size + payload size) 
   print ("size = ", headerInstance.size) 
 
   # read the rest of the body (payload size) 
   sizeToRead = headerInstance.size - headerSize 
   data = file.read(sizeToRead) 
 
print ("Finished with: ", numOfRecords, " Records") 

问题是使用read 或cast 函数时,在小端而不是大端进行。

如何读取或转换为 Big Endian?

请您参考如下方法:

ctypes.Structure 用于 native 字节顺序。

派生自 ctypes.BigEndianStructure 而不是 ctypes.Structure,但请注意 the documentation 中的警告:

Structures with non-native byte order cannot contain pointer type fields, or any other data types containing pointer type fields.