Python Hex String to Integer Array or List

4/5 - (1 vote)

Problem Formulation

Given a hex string, i.e., a string of hexadecimal digits like so:

01ffa87135affcd45deebe

You want to convert a batch of k hex digits to an integer. For example with k=2, you obtain the following batches of two hex digits each:

01 ff a8 71 35 af fc d4 5d ee be

Now, convert each of those pairs of hex digits to an integer:

[1, 255, 168, 113, 53, 175, 252, 212, 93, 238, 190]

Note that if you’re looking to convert such a hex string to NumPy array, check out this tutorial instead.

One-Liner Solution

The following one-liner iterates over each k-th position of the hex string and bundles together k subsequent hex digits. It converts each of those hex digits to an integer using int(..., base=16) in a list comprehension statement.

[int(hex_str[i:i+k], base=16) for i in range(0, len(hex_str), k)]

Here’s the minimal code example:

def hex_to_int_list(hex_str, k):
    ''' Aggregates bundles of k subsequent
        hex digits to one integer. Yields a list of ints.'''
    return [int(hex_str[i:i+k], base=16) for i in range(0, len(hex_str), k)]

print(hex_to_int_list('01ffa87135affcd45deebe', 2))
# [1, 255, 168, 113, 53, 175, 252, 212, 93, 238, 190]

If you love one-liners like I do, check out my book Python One-Liners!

If not, keep reading for the not-so-concise multi-liner solution. πŸ™‚

Multi-Liner Solution

You can use a for loop to iterate over the k-th indices using the range() function like before.

def hex_to_int_list(hex_str, k):
    ''' Aggregates bundles of k subsequent
        hex digits to one integer. Yields a list of ints.'''
    lst = []
    for i in range(0, len(hex_str), k):
        x = hex_str[i:i+k]
        x_int = int(x, base=16)
        lst.append(x_int)
    return lst


print(hex_to_int_list('01ffa87135affcd45deebe', 2))
# [1, 255, 168, 113, 53, 175, 252, 212, 93, 238, 190]

You use slicing hex_str[i:i+k] to batch k digits at a time to a substring and convert it to an integer.

You use the list append() method to add one integer at a time to the list of ints.

You return a list of integers. If you want to return an array of integers, simply convert the list to a NumPy array using the np.array(lst) function call:

import numpy as np


def hex_to_int_list(hex_str, k):
    ''' Aggregates bundles of k subsequent
        hex digits to one integer. Yields a list of ints.'''
    lst = []
    for i in range(0, len(hex_str), k):
        x = hex_str[i:i+k]
        x_int = int(x, base=16)
        lst.append(x_int)
    return np.array(lst)


print(hex_to_int_list('01ffa87135affcd45deebe', 2))
# [  1 255 168 113  53 175 252 212  93 238 190]

Let’s use two different values for k, i.e., k=1 and k=4:

print(hex_to_int_list('01ffa87135affcd45deebe', 1))
# [ 0  1 15 15 10  8  7  1  3  5 10 15 15 12 13  4  5 13 14 14 11 14]

print(hex_to_int_list('01ffa87135affcd45deebe', 4))
# [  511 43121 13743 64724 24046   190]

Works too! πŸ™‚


Thanks for reading through the whole tutorial! ❀️ To keep learning, feel free to join my free email academy — we have cheat sheets too!

Also, you may enjoy reading my best-selling Python training book:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!