hex string to character in python

后端 未结 4 1158
心在旅途
心在旅途 2021-01-01 20:37

I have a hex string like:

data = \"437c2123\"

I want to convert this string to a sequence of characters according to the ASCII table. The

相关标签:
4条回答
  • 2021-01-01 20:39

    The ord function converts characters to numerical values and the chr function does the inverse. So to convert 97 to "a", do ord(97)

    0 讨论(0)
  • 2021-01-01 20:55

    Since Python 2.6 you can use simple:

    data_con = bytes.fromhex(data)
    
    0 讨论(0)
  • 2021-01-01 21:03
    In [17]: data = "437c2123"
    
    In [18]: ''.join(chr(int(data[i:i+2], 16)) for i in range(0, len(data), 2))
    Out[18]: 'C|!#'
    

    Here:

    • for i in range(0, len(data), 2) iterates over every second position in data: 0, 2, 4 etc.
    • data[i:i+2] looks at every pair of hex digits '43', '7c', etc.
    • chr(int(..., 16)) converts the pair of hex digits into the corresponding character.
    • ''.join(...) merges the characters into a single string.
    0 讨论(0)
  • 2021-01-01 21:04

    In Python2

    >>> "437c2123".decode('hex')
    'C|!#'
    

    In Python3 (also works in Python2, for <2.6 you can't have the b prefixing the string)

    >>> import binascii
    >>> binascii.unhexlify(b"437c2123")
    b'C|!#'
    
    0 讨论(0)
提交回复
热议问题