开发者

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

开发者 https://www.devze.com 2022-12-22 00:21 出处:网络
I have a list of hex bytes strings like this [\'BB\', \'A7\', \'F6\', \'9E\'] (as read from a text file)

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开发者_Go百科 to this format?

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


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


[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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号