我有一个包含多种结构类型的二进制文件。 该文件包含大端数据。你知道吗
我正在读取文件并打印文件中的记录总数。 (有多种类型的结构,每种结构都有不同的尺寸)
下面是我的代码示例:
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
函数时,使用的是Little endian,而不是Big endian。你知道吗
我怎样才能读到或投出大端?你知道吗
ctypes.Structure
表示本机字节顺序。你知道吗从
ctypes.BigEndianStructure
而不是ctypes.Structure
派生,但请注意the documentation中的警告:相关问题 更多 >
编程相关推荐