binascii.unhexlify 的奇数长度字符串错误

Odd-length string error with binascii.unhexlify

我正在尝试将 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: Odd-length string

问题是什么,我该如何解决?

使用 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'
                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.