Skip to main content
 首页 » 编程设计

python之BitString之无法在 BitStream 中加载我的值

2024年10月24日9虾米姐

一个简单的问题。

我有一个 <\class 'str'>(选中),其中包含一个名为 hexapacket 的 124 长度六边形内容。

我是这样做的:

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:] 处理了它 但它仍然不适用于位串中的 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) 和 type(hexapacket) 的输出:

'0ed93a0002118b11a8050c04053e03bcd154bb84543c9b2a7992280bddf099b126acd1e75bf274842565e499d9e0221f86c02fa26d0a859ce426e63a74' 

和

<class 'str'> 

回答:使用 Python3.x 的 BitString 模块,它更容易转换和读取数据。

请您参考如下方法:

如果您指定 hex= 关键字参数,它应该可以工作:

>>> import bitstring 
>>> bitstring.BitStream(hex='0edd0e000201a9017dc0c3898000000000') 
BitStream('0x0edd0e000201a9017dc0c3898000000000')