Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Easiest Way to Convert List of Hex Strings to List of Integers
1
Easiest Way to Convert List of Hex Strings to List of Integers

5/5 – (1 vote)

[Image: 1f4ac.png] Question: Given a Python list of hexadecimal strings such as
Code:
['ff', 'ef', '0f', '0a', '93']
. How to convert it to a list of integers in Python such as
Code:
[255, 239, 15, 10, 147]
?

Easiest Answer

[Image: image-266-1024x559.png]

The easiest way to convert a list of hex strings to a list of integers in Python is the list comprehension statement
Code:
[int(x, 16) for x in my_list]
that applies the built-in function
Code:
int()
to convert each hex string to an integer using the hexadecimal base
Code:
16
, and repeats this for each hex string
Code:
x
in the original list.

Here’s a minimal example:

Code:
my_list = ['ff', 'ef', '0f', '0a', '93'] my_ints = [int(x, 16) for x in my_list] print(my_ints) # [255, 239, 15, 10, 147]

The list comprehension statement applies the expression
Code:
int(x, 16)
to each element
Code:
x
in the list
Code:
my_list
and puts the result of this expression in the newly-created list.

The
Code:
int(x, 16)
expression converts a hex string to an integer using the hexadecimal base argument
Code:
16
. A semantically identical way to write this would be
Code:
int(x, base=16)
.

In fact, there are many more ways to convert a hex string to an integer—each of them could be used in the expression part of the list comprehension statement.

However, I’ll show you one completely different approach to solving this problem without listing each and every combination of possible solutions. [Image: 1f447.png]

For Loop with List Append

You can create an empty list and add one hex integer at a time in the loop body after converting it from the hex string
Code:
x
using the
Code:
eval('0x' + x)
function call. This first creates a hexadecimal string with
Code:
'0x'
prefix using string concatenation and then lets Python evaluate the string as if it was real code and not a string.

Here’s an example:

Code:
my_list = ['ff', 'ef', '0f', '0a', '93'] my_ints = [] for x in my_list: my_ints.append(eval('0x' + x)) print(my_ints) # [255, 239, 15, 10, 147]

You use the fact that Python automatically converts a hex value of the form
Code:
0xff
to an integer
Code:
255
:

Code:
>>> 0xff 255 >>> 0xfe 254 >>> 0x0f 15

You may want to check out my in-depth guide on this important function for our solution:

[Image: 1f30d.png] Recommended Tutorial: Python
Code:
eval()
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: