8

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
  • 81
  • 1
  • 1
  • 2

3 Answers3

9
[int(x, 16) for x in L]
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
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
  • 114,847
  • 26
  • 189
  • 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
  • 281,034
  • 50
  • 354
  • 495