Python: How to convert a string containing hex bytes to a hex string

后端 未结 2 1396
有刺的猬
有刺的猬 2020-12-16 14:31

I\'m thinking binascii is the module I\'m looking for, but I can\'t quite seem to get the exact results for which I am looking.

Here\'s what I want to do. I want to

相关标签:
2条回答
  • 2020-12-16 15:02

    In all versions of Python, you can use the function binascii.a2b_hex() (also known as binascii.unhexlify()):

    >>> import binascii
    >>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
    >>> binascii.a2b_hex(s)
    '5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'
    

    In Python 3.x, you can use bytes.fromhex(s).

    In Python 2.x, you can use the hex str-to-str codec:

    >>> s.decode("hex")
    '5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'
    

    The codec internally calls binascii.a2b_hex().

    0 讨论(0)
  • 2020-12-16 15:09

    With binascii module:

    >>> from binascii import unhexlify
    >>> s = '356a192b7913b04c54574d18c28d46e6395428ab'
    >>> unhexlify(s)
    '5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab'
    
    0 讨论(0)
提交回复
热议问题