π¬ Question: How to convert a given hex string such as '0xF'
to a binary number such as '0b1111'
?
There are multiple variants of this problem depending on how you want the conversion and from which type to which type. In this article, we’ll go over the different methods from simple to more sophisticated.
Let’s get started! π
Hex to Binary
You can convert a hexadecimal number (not a string) with the prefix 0x
to a binary string using Python’s built-in function bin()
. For example, the expression bin(0xf)
yields the binary string '0b1111'
.
Let’s have a look at a couple of simple examples:
>>> bin(0xF) '0b1111' >>> bin(0x1) '0b1' >>> bin(0x2) '0b10' >>> bin(0x4) '0b100' >>> bin(0x8) '0b1000' >>> bin(0xfff) '0b111111111111' >>> bin(0x10000) '0b10000000000000000'
Hex to Binary Number
The type of the return value of the bin()
function is a string, i.e., binary representation of the binary number. For example, bin(0xf)
yields '0b1111'
and not 0b1111
.
>>> type(bin(0xfff)) <class 'str'>
To obtain a binary representation, you can simply pass the binary string into the eval()
function that essentially “runs” the string as a code snippet it represents.
Like so:
>>> eval(bin(0xfff)) 4095 >>> 0xfff 4095
This way, you can always convert the hex number to a binary and use the binary string representation as a binary number in your code at any point in time.
We still haven’t exactly answered the question of how to convert a hexadecimal string to a binary number in Python.
Hex String to Binary
If you pass a hexadecimal string instead of a hexadecimal number into the bin()
function, Python raises a TypeError: 'str' object cannot be interpreted as an integer
.
>>> bin(0xfff) '0b111111111111' >>> bin('0xfff') Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> bin('0xfff') TypeError: 'str' object cannot be interpreted as an integer
To fix this error and convert a hexadecimal string to a binary, you can first convert the hex string to a decimal using eval(hex_strin)
and pass the result into the bin()
function to convert it to a binary string:
>>> bin(eval('0xfff')) '0b111111111111'
The result is a binary string representation of the binary number. You can at any time convert it to an integer by passing it into the eval()
function once more.
>>> eval(bin(eval('0xfff'))) 4095 >>> eval('0xfff') 4095
As you can see, you could have saved yourself some effort by converting the hex string directly to an integer using the eval()
function only once.
π Recommended Tutorial: How to Write a Hex String as Binary Data & Binary File in Python?
Convert Hex to Binary with Leading Digits
To convert a hexadecimal string to a binary string with leading '0'
digits, you can use the zfill()
function on the result of the bin()
function after using slicing bin(...)[2:]
to get rid of the '0b'
binary prefix.
π‘ The zfill()
string method fills the string from the left with "0"
characters.
>>> bin(int(hex_string, 16))[2:].zfill(20) '00000000111111111111' >>> bin(int(hex_string, 16))[2:].zfill(100) '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111'
The resulting strings are not too useful without adding back the '0b'
prefix.
However, a simple string concatenation exercise can do that—so that you can pass the resulting binary string back to the eval()
function, for example.
In the following code snippet, I have highlighted the line to fix the SyntaxError
of using a binary number without '0b'
prefix:
>>> my_binary = bin(int(hex_string, 16))[2:].zfill(100) >>> my_binary '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111' >>> eval(my_binary) Traceback (most recent call last): File "<pyshell#60>", line 1, in <module> eval(my_binary) File "<string>", line 1 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111 ^ SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers >>> eval('0b' + my_binary) 4095
Hex String to Bytes Object Using unhexlify()
You can also import the binasccii
library that is built in your standard Python installation and run binascii.unhexlify(hex_str)
to get a bytes object as a result.
import binascii hex_str = 'ffff' bin_str = binascii.unhexlify(hex_str) print(bin_str) # b'\xff\xff' print(type(bin_str)) # <class 'bytes'>
However, you should not pass a hex string in the format '0xffff'
into it or it will raise a binascii.Error: Non-hexadecimal digit found
. Instead pass a hex string in the format 'ffff'
without leading '0x'
prefix.
In general, I’d prefer the following method to solve this problem (hex to bytes) because no library import is needed:
Bytes fromhex()
To convert a hexadecimal string to a bytes
object, you can use the bytes.fromhex()
function and pass the hex_string
into it as a single argument. No '0x'
prefix needed as well!
Here’s a simple example:
hex_str = 'ffff' bin_str = bytes.fromhex(hex_str) print(bin_str) # b'\xff\xff' print(type(bin_str)) # <class 'bytes'>
f-String for Hex to Binary Conversion
You can use the f-String expression f'{0xfff:0>100b}'
to convert the hexadecimal number 0xfff
to a binary number with 100
leading 0
s.
Here’s an example:
>>> f'{0xfff:0>100b}' '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111'
You can see what the different parts of the f-string mean by breaking it up like so:
>>> number, pad, rjust, size, kind = 0xfff, '0', '>', 100, 'b' >>> f'{number:{pad}{rjust}{size}{kind}}' '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111'
You can learn more about f-Strings in our full tutorial on the Finxter blog.
Source: This code snippet was inspired by the great SO answer from here.
Where to Go From Here
Thanks for reading through the whole tutorial — and for spending your valuable time with us. We’d love to keep you active as a learner in our free email academy.
Join us and download your cheat sheets here: