如何以Big-Endian格式读取和解析二进制文件

2024-03-28 13:00:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多种结构类型的二进制文件。 该文件包含大端数据。你知道吗

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

下面是我的代码示例:

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")

问题是,使用readcast函数时,使用的是Little endian,而不是Big endian。你知道吗

我怎样才能读到或投出大端?你知道吗


Tags: 文件theimportreaddatasize结构file
1条回答
网友
1楼 · 发布于 2024-03-28 13:00:11

ctypes.Structure表示本机字节顺序。你知道吗

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.

相关问题 更多 >