我正在为二进制格式编写解析器.这种二进制格式涉及不同的表,这些表再次是二进制格式,通常包含不同的字段大小(大约在50到100之间).
这些结构中的大多数将具有位域,并且在用C表示时将看起来像这些:
struct myHeader
{
unsigned char fieldA : 3
unsigned char fieldB : 2;
unsigned char fieldC : 3;
unsigned short fieldD : 14;
unsigned char fieldE : 4
}
Run Code Online (Sandbox Code Playgroud)
我遇到了struct模块,但意识到它的最低分辨率是一个字节而不是一点,否则该模块几乎适合这项工作.
我知道使用ctypes支持位域,但我不知道如何在这里连接包含位域的ctypes结构.
我的另一个选择是自己操作这些位并将其提供给字节并将其与struct模块一起使用 - 但由于我有接近50-100种不同类型的此类结构,因此编写代码变得更容易出错.我也担心效率,因为这个工具可能用于解析大千兆字节的二进制数据.
谢谢.
我正在搞乱制作二进制数据解析器,虽然我可以回到C,但我想看看我是否可以使用Python来完成任务.
我对如何实现这一点有所了解,我当前的实现看起来像这样:
from ctypes import *
class sHeader(Structure):
_fields_ = [("CC", c_uint8, 4),
("AFC", c_uint8, 2),
("TSC", c_uint8, 2),
("PID", c_uint16, 13),
("TP", c_uint16, 1),
("PSI", c_uint16, 1),
("TEI", c_uint16, 1),
("SyncByte", c_uint8)]
class Header(Union):
_fields_ = [("sData", sTsHeader),
("ulData", c_uint32)]
head = Header()
head.ulData = 0xffffffff
print(head.ulData)
print(head.sData.SyncByte)
print(sHeader.SyncByte)
print(sHeader.TEI)
print(sHeader.PSI)
print(sHeader.TP)
print(sHeader.PID)
print(sHeader.TSC)
print(sHeader.AFC)
print(sHeader.CC)
print(sizeof(sHeader))
print(sizeof(c_uint8))
print(sizeof(c_uint16))
print(sizeof(c_uint32))
Run Code Online (Sandbox Code Playgroud)
哪个产生这个输出:
V:\>C:\Python27\python.exe WidiUnpacker.py
0xffffffffL
0x0
<Field type=c_ubyte, ofs=4, size=1>
<Field type=c_ushort, ofs=2:15, bits=1>
<Field type=c_ushort, ofs=2:14, bits=1>
<Field type=c_ushort, …Run Code Online (Sandbox Code Playgroud) 我想将表示寄存器的压缩数组传递给接受a的C函数(在DLL中)char *.这是我到目前为止的代码:
from ctypes import *
class BitField():
def __init__(self,position,size):
self.position = position
self.size = size
class Reg1(BitField):
self.dll = "win32.dll"
self.B6 = BitField(self,58,6)
self.B5 = BitField(self,54,4)
self.B4 = BitField(self,48,6)
self.B3 = BitField(self,36,12)
self.B2 = BitField(self,24,12)
self.B1 = BitField(self,16,8)
self.B0 = BitField(self,0,16)
pack_register(Reg1,(expects a tuple)):
pass # created a stub , need help on this
#I want to pack the to 64 bit data, by padding all other zero's,
#if none of bit #fields specified by user.
obj …Run Code Online (Sandbox Code Playgroud) python ×4
ctypes ×2
struct ×2
binary-data ×1
bit-fields ×1
bitset ×1
byte ×1
java ×1
string ×1
unions ×1