π¬ Question: How to convert a hexadecimal string such as "00-ff-ef-01-0f-0a-1a"
to a NumPy array of integers [ 0 255 239 1 15 10 26]
?
Method 1: Hex String to List to NumPy Array
You can solve this problem easily by breaking it into two easier ones:
- First, convert the hex string to a list.
- Second, convert the list to a NumPy array.
Here’s the code:
import numpy as np hex_str = "00-ff-ef-01-0f-0a-1a" # 1. Convert hex string to list hex_lst = [int(x, base=16) for x in hex_str.split('-')] # 2. Convert list to array hex_arr = np.array(hex_lst) print(hex_arr) # [0 255 239 1 15 10 26]
Method 2: Use NumPy fromiter()
You can also convert a hex string to a NumPy array by using a generator expression inside the np.fromiter()
function call.
import numpy as np hex_str = "00-ff-ef-01-0f-0a-1a" hex_arr = np.fromiter((int(x, 16) for x in hex_str.split('-')), dtype=np.int64) print(hex_arr) # [ 0 255 239 1 15 10 26]
This looks similar to Method 1. Personally, I like Method 1 more because it uses a more well-known and easier function np.array()
instead of np.fromiter()
.
Let’s make sure that the data type is indeed a NumPy array using the built-in type()
function:
print(type(hex_arr)) # <class 'numpy.ndarray'>
Yay! π
If you didn’t find the answer to your question, you may want to look into my related article that shows a more generalized way to convert a hex string digit by digit to an integer list or array. See here:
π Recommended Tutorial: Python Hex String to Integer Array or List