7

I have a list of hex bytes strings like this

['BB', 'A7', 'F6', '9E'] (as read from a text file)

How do I convert that list to this format?

[0xBB, 0xA7, 0xF6, 0x9E]

pyNewGuy
  • 71
  • 1
  • 1
  • 2

4 Answers4

10
[int(x, 16) for x in L]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

[0xBB, 0xA7, 0xF6, 0x9E] is the same as [187, 167, 158]. So there's no special 'hex integer' form or the like.

But you can convert your hex strings to ints:

>>> [int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]
[187, 167, 246, 158]

See also Convert hex string to int in Python

Community
  • 1
  • 1
Ben James
  • 121,135
  • 26
  • 193
  • 155
4

Depending on the format in the text file, it may be easier to convert directly

>>> b=bytearray('BBA7F69E'.decode('hex'))

or

>>> b=bytearray('BB A7 F6 9E'.replace(' ','').decode('hex'))
>>> b
bytearray(b'\xbb\xa7\xf6\x9e')
>>> b[0]
187
>>> hex(b[0])
'0xbb'
>>> 

a bytearray is easily converted to a list

>>> list(b) == [0xBB, 0xA7, 0xF6, 0x9E]
True

>>> list(b)
[187, 167, 246, 158]

If you want to change the way the list is displayed you'll need to make your own list class

>>> class MyList(list):
...  def __repr__(self):
...   return '['+', '.join("0x%X"%x if type(x) is int else repr(x) for x in self)+']'
... 
>>> MyList(b)
[0xBB, 0xA7, 0xF6, 0x9E]
>>> str(MyList(b))
'[0xBB, 0xA7, 0xF6, 0x9E]'
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

For others coming across this answer...

If you happen to have a string of space-separated hex values like the following:

test_str = "13 14 15 16 17 18 19"

you can just use:

byte_array = bytearray.fromhex(test_str)
print(byte_array)

bytearray(b'\x13\x14\x15\x16\x17\x18\x19')

Or convert it to a decimal values list with:

print(list(byte_array))

[19, 20, 21, 22, 23, 24, 25]
Sean McCarthy
  • 4,838
  • 8
  • 39
  • 61