TypeError:解码十六进制字符串时的奇数长度字符串

时间:2014-12-25 16:04:31

标签: python string python-2.7 hex decode

我已经确定字符串被剥离了,我仍然会遇到奇数字符串问题。有人可以告诉我我做错了吗?

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> toSend.decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string
>>> 

1 个答案:

答案 0 :(得分:8)

字符串中的空格使decode方法混乱。如果删除它们,您的代码将起作用:

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> toSend.replace(' ', '').decode('hex')
'\xff\xf9\xff\x00\x00\xfa\xff\xf7\xff\xf4\xff\xf6\xff\xf7\xff\xf6\xff\xfd\xff\x05\x00\x03\x00\x06\x00\x05\x00\x04\x00\x06\x00\x06\x00\x03\x00\xfb\xff\x02\x00\x0b'
>>>

或者,如果您必须拥有它们,请使用str.join和列表理解:

>>> toSend = "FF F9 FF 00 00 FA FF F7 FF F4 FF F6 FF F7 FF F6 FF FD FF 05 00 03 00 06 00 05 00 04 00 06 00 06 00 03 00 FB FF 02 00 0B"
>>> ' '.join([x.decode('hex') for x in toSend.split()])
'\xff \xf9 \xff \x00 \x00 \xfa \xff \xf7 \xff \xf4 \xff \xf6 \xff \xf7 \xff \xf6 \xff \xfd \xff \x05 \x00 \x03 \x00 \x06 \x00 \x05 \x00 \x04 \x00 \x06 \x00 \x06 \x00 \x03 \x00 \xfb \xff \x02 \x00 \x0b'
>>>