Python Hex String to NumPy Array

5/5 - (1 vote)

πŸ’¬ 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:

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)

# [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)

# [  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:

# <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