For solving the left-side trailing zero problem:


my_hexdata = "1a"

scale = 16 ## equals to hexadecimal

num_of_bits = 8

bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)

It will give 00011010 instead of the trimmed version.

Answer from Onedinkenedi on Stack Overflow
Top answer
1 of 16
160

For solving the left-side trailing zero problem:


my_hexdata = "1a"

scale = 16 ## equals to hexadecimal

num_of_bits = 8

bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)

It will give 00011010 instead of the trimmed version.

2 of 16
90

Convert hex to binary

I have ABC123EFFF.

I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).

Short answer:

The new f-strings in Python 3.6 allow you to do this using very terse syntax:

>>> f'{0xABC123EFFF:0>42b}'
'001010101111000001001000111110111111111111'

or to break that up with the semantics:

>>> number, pad, rjust, size, kind = 0xABC123EFFF, '0', '>', 42, 'b'
>>> f'{number:{pad}{rjust}{size}{kind}}'
'001010101111000001001000111110111111111111'

Long answer:

What you are actually saying is that you have a value in a hexadecimal representation, and you want to represent an equivalent value in binary.

The value of equivalence is an integer. But you may begin with a string, and to view in binary, you must end with a string.

Convert hex to binary, 42 digits and leading zeros?

We have several direct ways to accomplish this goal, without hacks using slices.

First, before we can do any binary manipulation at all, convert to int (I presume this is in a string format, not as a literal):

>>> integer = int('ABC123EFFF', 16)
>>> integer
737679765503

alternatively we could use an integer literal as expressed in hexadecimal form:

>>> integer = 0xABC123EFFF
>>> integer
737679765503

Now we need to express our integer in a binary representation.

Use the builtin function, format

Then pass to format:

>>> format(integer, '0>42b')
'001010101111000001001000111110111111111111'

This uses the formatting specification's mini-language.

To break that down, here's the grammar form of it:

[[fill]align][sign][#][0][width][,][.precision][type]

To make that into a specification for our needs, we just exclude the things we don't need:

>>> spec = '{fill}{align}{width}{type}'.format(fill='0', align='>', width=42, type='b')
>>> spec
'0>42b'

and just pass that to format

>>> bin_representation = format(integer, spec)
>>> bin_representation
'001010101111000001001000111110111111111111'
>>> print(bin_representation)
001010101111000001001000111110111111111111

String Formatting (Templating) with str.format

We can use that in a string using str.format method:

>>> 'here is the binary form: {0:{spec}}'.format(integer, spec=spec)
'here is the binary form: 001010101111000001001000111110111111111111'

Or just put the spec directly in the original string:

>>> 'here is the binary form: {0:0>42b}'.format(integer)
'here is the binary form: 001010101111000001001000111110111111111111'

String Formatting with the new f-strings

Let's demonstrate the new f-strings. They use the same mini-language formatting rules:

>>> integer = 0xABC123EFFF
>>> length = 42
>>> f'{integer:0>{length}b}'
'001010101111000001001000111110111111111111'

Now let's put this functionality into a function to encourage reusability:

def bin_format(integer, length):
    return f'{integer:0>{length}b}'

And now:

>>> bin_format(0xABC123EFFF, 42)
'001010101111000001001000111110111111111111'    

Aside

If you actually just wanted to encode the data as a string of bytes in memory or on disk, you can use the int.to_bytes method, which is only available in Python 3:

>>> help(int.to_bytes)
to_bytes(...)
    int.to_bytes(length, byteorder, *, signed=False) -> bytes
...

And since 42 bits divided by 8 bits per byte equals 6 bytes:

>>> integer.to_bytes(6, 'big')
b'\x00\xab\xc1#\xef\xff'
🌐
Joernhees
joernhees.de › blog › 2010 › 09 › 21 › how-to-convert-hex-strings-to-binary-ascii-strings-in-python-incl-8bit-space
How to convert hex strings to binary ascii strings in python (incl. 8bit space) | Jörn's Blog
>>> binary = lambda x: " ".join(reversed( [i+j for i,j in zip( *[ ["{0:04b}".format(int(c,16)) for c in reversed("0"+x)][n::2] for n in [1,0] ] ) ] )) >>> binary("c3a4c3b6c3bc") '11000011 10100100 11000011 10110110 11000011 10111100' It takes the hex string x, first of all concatenates a "0" to the left (for the uneven case), then reverses the string, converts every char into a 4-bit binary string, then collects all uneven indices of this list, zips them to all even indices, for each in the pairs-list concatenates them to 8-bit binary strings, reverses again and joins them together with a ” ” in between.
Discussions

python - Converting hex to binary in the form of string - Code Review Stack Exchange
You don't have a lot of code here to review, so this will necessarily be short. PEP-8: The Style Guide for Python Code recommends: snake_case for functions, variables, and parameters. So aString should be a_string, and retVal should be ret_val. ... What is aString? "Hello World" is a string, but we can't use it, because you are actually expecting a hexadecimal string. Perhaps hex_string would be a better parameter name. Similarly, binary... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
May 1, 2021
Python conversion from binary string to hexadecimal - Stack Overflow
How can I perform a conversion of a binary string to the corresponding hex value in Python? I have 0000 0100 1000 1101 and I want to get 048D I'm using Python 2.6. More on stackoverflow.com
🌐 stackoverflow.com
Write a hex string as binary data in Python - Stack Overflow
Copy>>> ss = '7e7e303035f8350d013d0a' ... >>> bytes.hex(bb) '7e7e303035f8350d013d0a' ... Save this answer. ... Show activity on this post. In Python 3.x you can just use the b prefix in front of modified form of the string, and then write it out to a binary file like ... More on stackoverflow.com
🌐 stackoverflow.com
python convert hex string to formated binary string - Stack Overflow
From input 0x1234 I need to output: 0b0001_0010_0011_0100. I can think of all the bad ways to do this, but what's the most pythonic way to achieve this. I can easily convert to bin string (bin(i... More on stackoverflow.com
🌐 stackoverflow.com
April 16, 2017
🌐
Quora
quora.com › How-do-you-convert-hex-to-binary-in-the-form-of-string-Python-solutions
How to convert hex to binary in the form of string (Python, solutions) - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-ways-to-convert-hex-into-binary
Python - Ways to convert hex into binary - GeeksforGeeks
July 12, 2025 - Python · a = "1A3" # Convert to binary using format() b = format(int(a, 16), 'b') print("Binary:", b) Output · Binary: 110100011 · Explanation: int(a, 16) converts the hexadecimal string "1A3" to its corresponding integer value. format(int(a, ...
🌐
Finxter
blog.finxter.com › home › learn python blog › python convert hex string to binary
Python Convert Hex String to Binary - Be on the Right Side of Change
November 26, 2022 - You can convert a hexadecimal number (not a string) with the prefix 0x to a binary string using Python’s built-in function bin().
🌐
alpharithms
alpharithms.com › home › tutorials › how to convert hexadecimal values to binary in python
How to Convert Hexadecimal Values to Binary in Python - αlphαrithms
June 16, 2022 - 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
Top answer
1 of 3
5

Review

You don't have a lot of code here to review, so this will necessarily be short.

  • PEP-8: The Style Guide for Python Code recommends:
    • snake_case for functions, variables, and parameters. So aString should be a_string, and retVal should be ret_val.
  • Better parameter names
    • What is aString? "Hello World" is a string, but we can't use it, because you are actually expecting a hexadecimal string. Perhaps hex_string would be a better parameter name.
    • Similarly, binary_string would be more descriptive than retStr.
  • A '''docstring''' would be useful for the function.
  • Type hints would also be useful.

Alternate Implementation

Doing things character-by-character is inefficient. It is usually much faster to let Python do the work itself with its efficient, optimized, native code functions.

Python strings formatting supports adding a comma separator between thousand groups.

>>> f"{123456789:,d}"
'123,456,789'

It also supports adding underscores between groups of 4 digits when using the binary or hexadecimal format codes:

>>> f"{548151468:_x}"
'20ac_20ac'
>>> f"{0x20AC:_b}"
'10_0000_1010_1100'

That is most of the way to what you're looking for. Just need to turn underscores to spaces, with .replace(...) and fill with leading zeros by adding the width and 0-fill flag to the format string.

>>> f"{0x20AC:019_b}".replace('_', ' ')
'0010 0000 1010 1100'

A function using this technique could look like:

def str_bin_in_4digits(hex_string: str) -> str:
    """
    Turn a hex string into a binary string.
    In the output string, binary digits are space separated in groups of 4.

    >>> str_bin_in_4digits('20AC')
    '0010 0000 1010 1100'
    """

    value = int(hex_string, 16)
    width = len(hex_string) * 5 - 1
    bin_string = f"{value:0{width}_b}"
    return bin_string.replace('_', ' ')

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)

Depending on your definition of elegant, you can one-line this:

def str_bin_in_4digits(hex_string: str) -> str:
    """
    Turn a hex string into a binary string.
    In the output string, binary digits are space separated in groups of 4.

    >>> str_bin_in_4digits('20AC')
    '0010 0000 1010 1100'
    """

    return f"{int(hex_string,16):0{len(hex_string)*5-1}_b}".replace('_', ' ')
2 of 3
3

The problem is to take a hex string and convert it to the equivalent binary string. Each character in the input string maps to a one or more characters in the output string, e.g., '0' -> '0000', ... 'A' -> '1010', ... 'F' -> '1111'. This is a perfect fit for string.translate()

table = ''.maketrans({'0':'0000 ', '1':'0001 ', '2':'0010 ', '3':'0011 ',
                      '4':'0100 ', '5':'0101 ', '6':'0110 ', '7':'0111 ',
                      '8':'1000 ', '9':'1001 ', 'A':'1010 ', 'B':'1011 ',
                      'C':'1100 ', 'D':'1101 ', 'E':'1110 ', 'F':'1111 '})


def str_bin_in_4digits(hex_string):
    return hex_string.upper().translate(table)

It's 6-7 times faster.

Find elsewhere
🌐
CodingTechRoom
codingtechroom.com › question › convert-hex-to-binary-python
How to Convert a Hexadecimal String to a Binary String in Python - CodingTechRoom
hex_string = '1A3F' binary_string = bin(int(hex_string, 16))[2:] # Convert hex to binary, strip the '0b' prefix print(binary_string) # Output: '110100011111'
🌐
Javatpoint
javatpoint.com › how-to-convert-hexadecimal-to-binary-in-python
How to convert hexadecimal to binary in python - Javatpoint
How to convert hexadecimal to binary in python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
Python
mail.python.org › pipermail › tutor › 2002-April › 013457.html
[Tutor] How can I convert hex string to binary string?
September 1, 2013 - # # hex2bin # def hex2bin(str): bin = ['0000','0001','0010','0011', '0100','0101','0110','0111', '1000','1001','1010','1011', '1100','1101','1110','1111'] aa = '' for i in range(len(str)): aa += bin[atoi(str[i],base=16)] return aa # End >>>hex2bin('0a0b') '0000101000001011' # Regards Ares ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Ares Liu" <Ares.liu@Clarent.com> Cc: <tutor@python.org> Sent: Wednesday, April 03, 2002 3:44 PM Subject: Re: [Tutor] How can I convert hex string to binary string?
🌐
LabEx
labex.io › questions › how-to-convert-hex-to-binary-702710
How to convert hex to binary? | LabEx
July 1, 2026 - Here's a Python code example that demonstrates this conversion: def hex_to_binary(hex_number): binary_num = bin(int(hex_number, 16))[2:] # Convert hex to binary and remove the '0b' prefix return binary_num.zfill(4 * len(hex_number)) # Ensure ...
🌐
CodeScracker
codescracker.com › python › program › python-program-convert-hexadecimal-to-binary.htm
Python Program to Convert Hexadecimal to Binary
class CodesCracker: def HexToBin(self, h): return bin(int(h, 16)) print("Enter the Hexadecimal Number: ", end="") hnum = input() obj = CodesCracker() bnum = obj.HexToBin(hnum) print("\nEquivalent Binary Value = ", bnum[2:]) In this program, an object named obj of class CodesCracker is created to access its member function named HexToBin() using dot (.) operator. Rest of the things works like a normal function. ... Test your programming and computer science knowledge with interactive MCQs and topic-based quizzes. All Quizzes SQL Quiz Python Quiz Java Quiz C++ Quiz
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-string-to-binary
Convert String to Binary - Python - GeeksforGeeks
July 12, 2025 - Python · import binascii txt = ... turns those bytes into a hexadecimal string · bin(int(..., 16))[2:] converts the hex string to binary, removing the '0b' prefix ·...
🌐
Finxter
blog.finxter.com › home › learn python blog › how to write a hex string as binary data & binary file in python?
How to Write a Hex String as Binary Data & Binary File in Python? - Be on the Right Side of Change
November 26, 2022 - You obtain the binary string from the hex string using the binascii.unhexlify(hex_string) function call. ... import binascii hex_str = 'FF0001AF' bin_str = binascii.unhexlify(hex_str) with open('hex_file.dat', 'wb') as f: f.write(bin_str) The ...
🌐
Python Forum
python-forum.io › thread-30139.html
Convert file of hex strings to binary file
October 9, 2020 - Hello, I have a file that has several hex string values, separated by the newline character. E.g. the file looks like: dd5bda81 ae0ac495 b97a7664 ...I can easily parse this file and find e.g. the 10th string based on the line number. However I want...