简体   繁体   中英

hex string to character in python

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 result should be like:

data_con = "C|!#"

Can anyone tell me how to do this?

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|!#'
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.

从Python 2.6开始,您可以使用简单的:

data_con = bytes.fromhex(data)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM