pyNewGuy
pyNewGuy

Reputation: 71

What's the easiest way to convert a list of hex byte strings to a list of hex integers?

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]

Upvotes: 7

Views: 33253

Answers (4)

Sean McCarthy
Sean McCarthy

Reputation: 5578

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]

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304355

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

Upvotes: 4

Ben James
Ben James

Reputation: 125217

[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

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

[int(x, 16) for x in L]

Upvotes: 10

Related Questions