2

一个简单的问题。

我有一个名为 hexapacket 的 124 长度六进制内容的 <\class 'str'> (选中)。

我正在这样做:

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:] 处理它但它仍然没有'不适用于位串中的位流。我准确地说原始数据包来自 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 模块,更容易转换和读取数据。

4

1 回答 1

2

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

>>> import bitstring
>>> bitstring.BitStream(hex='0edd0e000201a9017dc0c3898000000000')
BitStream('0x0edd0e000201a9017dc0c3898000000000')
于 2016-01-18T01:00:18.853 回答