【问题标题】:Odd-length string error with binascii.unhexlifybinascii.unhexlify 出现奇数字符串错误
【发布时间】:2017-05-06 23:10:36
【问题描述】:

我正在尝试将 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:奇数长度的字符串

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

【问题讨论】:

    标签: python-2.7 binary binascii


    【解决方案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'
    

    【讨论】:

    • 在开头或结尾处填充?
    【解决方案2】:
                    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.
    

    【讨论】:

      猜你喜欢
      • 2016-01-10
      • 2016-09-11
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 2012-08-15
      相关资源
      最近更新 更多