Conversion methods between Python hexstring list str

  • 2021-06-28 13:05:04
  • OfStack

When Python manipulates data content, in most cases it may encounter three types of data processing:

hexstring e.g.'1C532145697A8B6F8EN'

str e.g.'x1Cx53x21x45x69x7Ax8BES226F'

list e.g. [0x1C, 0x53, 0x21, 0x45, 0x69, 0x7A, 0x8B, 0x6F]

In various third-party modules (e.g. pyDes) or self-written interfaces, there may be situations where switching back and forth in these three types of data is required due to different types of 1.

The core methods to be used are as follows:

list() Converts an object to list

str() Converts an object to str

bytearray() Converts an object to bytearray

bytearray.fromhex() Converts an object from hexstring to bytearray

binascii.b2a_hex() Converts an object from str to hexstring

1. Shaping List to str

For example: [0x53, 0x21, 0x6A] - > '\x53\x21\x6a'

Method: list - > bytearray - > str


x = [0x53, 0x21, 0x6A]
y = str(bytearray(x))

2. str reshaping list

For example:'x53x216a'- > [0x53, 0x21, 0x6A]

Method: Convert character by character to 10-digit


x = '\x53\x21\x6a'
y = [ord(c) for c in x]

3. Convert the shaping list to hex string

For example: [0x53, 0x21, 0x6A] - > '53216A'

Method: list - > bytearray - > str - > hexstring


import binascii
x = [0x53, 0x21, 0x6A]
y = str(bytearray(x))
z = binascii.b2a_hex(y)

4. hex string converted to a reshaped list

For example:'53216A'- > [0x53, 0x21, 0x6A]

Method: hexstring - > bytearray - > list


x = '53216A'
y = bytearray.fromhex(x)
z = list(y)

5. hex string to str

For example:'53216A'- > '\x53\x21\x6A'

Method: hexstring - > bytearray - > str


x = '53216A'
y = bytearray.fromhex(x)
z = str(y)

Related articles: