一个简单的问题。
我有一个< \ class' str'> (选中)使用名为hexapacket的124长度hexa内容。
我这样做:
import bitstring
data = BitStream(hexa=hexapacket)
# My processing on bits
但它会引发错误,因为它无法找到长度等等。
ValueError: invalid literal for int() with base 10: '0edd0e000201a9017dc0c3898000000000'
和
ValueError: Don't understand length '0edd0e000201a9017dc0c3898000000000' of token.
和
KeyError: ('0edd0e000201a9017dc0c3898000000000', 0)
你能帮忙让它运作吗?这是我想解析数据的解决方案。
编辑: 我尝试了一些调试,输出很奇怪,hex()强制转换和bin()强制转换在字符串的开头添加0b和0x,我用string = string [2:]处理它 但它仍然不能用bittring来处理BitStream。 我确切地说原始数据包来自pyshark并且我将packet.data.data转换为字符串。
代码:
if hexapacket.find(':') != -1:
hexapacket = ''.join(packet.split(":"))
if hexapacket.find('0x') != -1:
hexapacket = hexapacket[2:]
msgid = int(bin(int(hexapacket[:4],16))[2:-2],2)
messagetype = dict_ids[msgid]
lenoflen = int(bin(int(hexapacket[:4],16))[-2:],2)
print("ID: %d\nMSG: %s\nLoL: %d\n" % (msgid,messagetype,lenoflen))
print("My hexapacket\n%s" % hexapacket)
raw = BitStream(hex=hexapacket)
输出:
ID: 950
MSG: GameMapMovementRequestMessage
LoL: 1
My hexapacket
0ed93c0003519a418c418b050c0405fafb5a21348190b66ecc166c09f832a7324069fcd9e19ea6be654b26b42563908947857a2b3cb25ce920837262a5fb69
错误:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/bitstring.py", line 612, in tokenparser
length = int(length)
ValueError: invalid literal for int() with base 10: '0pad:0pad:0pad:0pad:0pad:0pad:0pad:0'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 232, in <module>
messages = PacketProcessing().splitProcess(packet)
File "main.py", line 182, in splitProcess
data1 = raw.read('pad:%d'%datalen*8)
File "/usr/local/lib/python3.5/site-packages/bitstring.py", line 3880, in read
_, token = tokenparser(fmt)
File "/usr/local/lib/python3.5/site-packages/bitstring.py", line 622, in tokenparser
raise ValueError("Don't understand length '{0}' of token.".format(length))
ValueError: Don't understand length '0pad:0pad:0pad:0pad:0pad:0pad:0pad:0' of token.
repr(hexapacket)和类型(hexapacket)的输出:
'0ed93a0002118b11a8050c04053e03bcd154bb84543c9b2a7992280bddf099b126acd1e75bf274842565e499d9e0221f86c02fa26d0a859ce426e63a74'
和
<class 'str'>
解答:对Python3.x使用BitString模块,可以更容易地投射和读取数据。
答案 0 :(得分:2)
如果您指定hex=
关键字参数:
>>> import bitstring
>>> bitstring.BitStream(hex='0edd0e000201a9017dc0c3898000000000')
BitStream('0x0edd0e000201a9017dc0c3898000000000')