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]
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.
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.
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);
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.
[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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With