tags:

views:

156

answers:

3

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]

+2  A: 
[int(x, 16) for x in L]
Ignacio Vazquez-Abrams
I think you mean `int(x, 16)`
Otto Allmendinger
+2  A: 

[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 http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python

Ben James
+3  A: 

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]'
gnibbler