Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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]

like image 313
pyNewGuy Avatar asked Mar 07 '10 19:03

pyNewGuy


People also ask

How do you convert a list of strings to a list of numbers?

This basic method to convert a list of strings to a list of integers uses three steps: Create an empty list with ints = [] . Iterate over each string element using a for loop such as for element in list . Convert the string to an integer using int(element) and append it to the new integer list using the list.

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.

How do you convert a hex string to a byte array?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);

How do I convert a list of elements to a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

[int(x, 16) for x in L]
like image 131
Ignacio Vazquez-Abrams Avatar answered Sep 16 '22 19:09

Ignacio Vazquez-Abrams


[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

like image 39
Ben James Avatar answered Sep 20 '22 19:09

Ben James