How to Convert Hexadecimal Values to Binary in Python

python convert hexadecimal to binary

Python has tools for nearly every computer-related task and converting hexadecimal values into binary values is no exception. In fact, this feat can be accomplished using standard library functions!

Quick Review

Hexadecimal values (a.k.a. base 16 numbers) consist of characters in the range of 1-9 and a-f. All total: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, g]  . Binary numbers (a.k.a. base 2 numbers) are much easier to remember: [0, 1]. Each of these stores data in ways that can be especially useful in certain contexts. Binary values are the basis for computer numerical representation but hexadecimal values let us represent larger values more conveniently, at least in most cases.

Converting Hexadecimal to Binary

When working with hexadecimal and binary data, one might find the need to convert from one to another. For example, mapped caches may use hexadecimal memory address values to calculate set number, index number, and offset values in binary form.

Note: The values are all interpreted as integers ultimately, but converting to binary can help during the design and debug phase of many low-level applications.

Cache design may be a poor example given the context of Python, but the utility is still here. Python is one of the world’s most popular programming languages for good reason: it can handle nearly everything—or at least find ways to accommodate. Below are several ways to convert hexadecimal values into Binary numbers in Python:

1. Using the bin Builtin

Python’s bin method converts an integer value into a binary value object. However, in the case that hexadecimal values include alphabetical characters (thus interpreted as a string) there’s an intermediate conversion that is required. For example:

# Define a hexadecimal value
hex_value = "1f"

# Convert to a binary value
bin(hex_value)

>>> TypeError: 'str' object cannot be interpreted as an integer

This signals that Python cannot convert a string value to a binary value directly. We must first convert the string to an integer value. To do this, we take advantage of the functionality of Python’s int data type and it’s acceptance of base value specifications.

# Define a hexadecimal value
hex_value = "1f"

# Convert to Integer
int_value = int(hex_value, base=16)
>>> 28

# Convert integer to a binary value
bin_value = bin(int_value)
>>> 0b11100

This gives us a binary object, with a binary value, but might not be what we’re looking for exactly. For starters, the 0b prefix might be too annoying to stick around. That can be remedied by converting to a string and slicing from the second character onward like so:

# Define a hexadecimal value
hex_value = "1c"

# Convert to Integer
int_value = int(hex_value, base=16)
>>> 28
type(int_value)
>>> <class 'int'>

# Convert integer to a binary value
binary_value = str(bin(int_value))[2:]
>>> 11100
type(binary_value)
>>> <class 'str'>

That’s looking closer to what most representations of binary numbers resemble, but there are only 5 digits. That’s because, by default, Python will display only enough digits to represent the most significant bit (MSB) and omit any leading 0’s.

Let’s say we’re working with 8-bit numbers and want to ensure all are displayed with a uniform number of bits. That means 8 digital places for 127 and 8 for 0. This can be accomplished using the builtin zfill() method of Python strings in conjunction with what we’ve already got:

# Define a hexadecimal value
hex_value = "1c"

# Convert to Integer
int_value = int(hex_value, base=16)
>>> 28

# Convert integer to a binary value
binary_value = str(bin(int_value))[2:].zfill(8)
>>> 00011100

That’s looking better! Python’s zfill function will add 0’s to a string if that string is less than the specified value in length. From the zfill docs:

Return a copy of the string left filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).

Putting Everything Together

The approach to convert a hexadecimal value into a binary value in Python is simple enough. Still, the syntax is clunky enough that it can prove beneficial to wrap everything up in a nice function, as seen below:

def hex_to_binary(hex_number: str, num_digits: int = 8) -> str:
    """
    Converts a hexadecimal value into a string representation
    of the corresponding binary value
    Args:
        hex_number: str hexadecimal value
        num_digits: integer value for length of binary value.
                    defaults to 8

    Returns:
        string representation of a binary number 0-padded
        to a minimum length of <num_digits>
    """
    return str(bin(int(hex_number, 16)))[2:].zfill(num_digits)

This function takes two arguments: the hexadecimal value and a num_digits argument representing the minimum length of the returned binary value. The num_digits is set to a default length of 8, such that one might easily work with 8-bit values. If working with 16, 32, or 64-bit values simply specify that as such: hex_to_binary("123abc", 16).

Note: this function is available on GitHub where you can fork your own version.

Review

Python’s toolset covers nearly every demand ranging from socket programming and bit shifting to statistical analysis and numerical conversions. Here we’ve seen how to use Python’s built-in bin and int datatypes as well as the str.zfill method to convert a hexadecimal value into a binary string. There are many other ways one can go about this but, in my opinion, this one involves the fewest number of dependencies and gets the job done well.

alpharithms discord banner 1
Zαck West
Entrepreneur, programmer, designer, and lifelong learner. Can be found taking notes from Mother Nature when not hammering away at the keyboard.