💬 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

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.