我正在尝试将ASCII字符串来回转换为二进制表示,如下所示。
s=chr(0)*15 + chr(0x01)
bst = bin(int(binascii.hexlify(s), 16))
n = int(bst, 2)
binascii.unhexlify('%x' % n)
但是,我在最后得到以下错误,这对我来说没什么意义。
1 binascii.unhexlify('%x'%n)
TypeError:奇数长度字符串
问题是什么?如何解决?
答案 0 :(得分:1)
使用python控制台:
>>> help(binascii.unhexlify)
unhexlify(...)
a2b_hex(hexstr) -> s; Binary data of hexadecimal representation.
hexstr must contain an even number of hex digits (upper or lower case).
This function is also available as "unhexlify()"
所以错误是一致的。你需要做的是用'0'
填充以得到偶数:
>>> binascii.unhexlify('0%x' % n)
'\x01'
答案 1 :(得分:0)
n = int(wer, 2)
qqwslenf=len(wer)
qqwslenf=(qqwslenf/8)*2
qqwslenf=str(qqwslenf)
qqwslenf="%0"+qqwslenf+"x"
jlz=binascii.unhexlify(qqwslenf % n)
#we convert from binary to ASCII exactly size of need by half bytes.