int given base 2 and then hex:

>>> int('010110', 2)
22
>>> hex(int('010110', 2))
'0x16'
>>> 

>>> hex(int('0000010010001101', 2))
'0x48d'

The doc of int:

int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating

point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If base is zero, the proper base is guessed based on the string content. If the argument is outside the integer range a long object will be returned instead.

The doc of hex:

hex(number) -> string

Return the hexadecimal representation of an integer or long

integer.

Answer from Eli Bendersky on Stack Overflow
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "python how-to's" › "how to convert binary to hex in python"
How to Convert Binary to Hex in Python | Delft Stack
February 2, 2024 - To convert binary to hexadecimal in Python, we can also use the int() function to first convert the binary string to an integer and then use the hex() function to obtain the hexadecimal representation.
Discussions

python - Convert hex to binary - Stack Overflow
Return the binary data represented by the hexadecimal string specified as the parameter. ... This returns "binary" as in the actual bytes, but it does not convert it to a printable representation as "0" and "1". 2009-09-15T06:52:04.77Z+00:00 ... docs.python.org/library/binascii.html is subtitled ... More on stackoverflow.com
🌐 stackoverflow.com
Python: binary/hex string conversion? - Stack Overflow
I have a string that has both binary and string characters and I would like to convert it to binary first, then to hex. ... How do I go about converting this string in Python so that the output in hex format is similar to this below? More on stackoverflow.com
🌐 stackoverflow.com
How do I convert a string of bits to a hex string in Python? - Stack Overflow
I have a bit-string of 32 characters that I need to represent as hexadecimal in Python. For example, the string "10000011101000011010100010010111" needs to also be output as "83A1A897". Any sugges... More on stackoverflow.com
🌐 stackoverflow.com
Code to convert from binary to hexadecimal
Posted by u/No_Ingenuity9213 - 2 votes and 3 comments More on reddit.com
🌐 r/Python
3
2
February 28, 2022
🌐
Quora
quora.com › How-can-I-convert-binary-to-hex-in-Python
How to convert binary to hex in Python - 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-program-to-convert-binary-to-hexadecimal
Python Program to Convert Binary to Hexadecimal | GeeksforGeeks
August 2, 2024 - In this article, we will learn how to convert a decimal value(base 10) to a hexadecimal value (base 16) in Python. Method 1: Using hex() function hex() function is one of the built-in functions in Python3, which is used to convert an integer ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert Binary, Octal, Decimal, and Hexadecimal in Python | note.nkmk.me
May 19, 2023 - Built-in Functions - format() — Python 3.11.3 documentation · You can convert a number to a binary, octal, or hexadecimal string by specifying b, o, or x in the format specification string, which is used as the second argument of format().
🌐
Python
docs.python.org › 3 › library › binascii.html
binascii — Convert between binary and ASCII
The returned bytes object is therefore twice as long as the length of data. Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method.
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'
Find elsewhere
🌐
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 - >>> bin(0xfff) '0b111111111111' ... 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:...
🌐
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.
🌐
Educative
educative.io › answers › how-to-convert-a-binary-number-to-hexadecimal-in-python
How to convert a binary number to hexadecimal in Python
Below is the coding implementation for the mentioned method, where we are converting a binary string to a decimal number and storing it as a variable named decimal_number: ... We're given a binary number. ... The hex method is the built-in function used to convert a decimal number to a hexadecimal number.
🌐
Reddit
reddit.com › r/python › code to convert from binary to hexadecimal
r/Python on Reddit: Code to convert from binary to hexadecimal
February 28, 2022 - def Hexdecimal_conv(a): if a == ["0", "0", "0", "0"]: return "0" if a == ["0", "0", "0", "1"]: return '1' if a == ["0", "0", "1", "0"]: return '2' if a == ["0", "0", "1", "1"]: return '3' if a == ["0", "1", "0", "0"]: return '4' if a == ["0", "1", "0", "1"]: return '5' if a == ["0", "1", "1", "0"]: return '6' if a == ["0", "1", "1", "1"]: return '7' if a == ["1", "0", "0", "0"]: return '8' if a == ["1", "0", "0", "1"]: return '9' if a == ["1", "0", "1", "0"]: return 'A' if a == ["1", "0", "1", "1"]: return 'B' if a == ["1", "1", "0", "0"]: return 'C' if a == ["1", "1", "0", "1"]: return 'D' if
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-convert-bytearray-to-hexadecimal-string-using-python
How to Convert Bytearray to Hexadecimal String using Python?
January 3, 2024 - For older Python versions, binascii.hexlify() offers good performance and simplicity for converting bytearrays to hexadecimal strings.
🌐
Stack Overflow
stackoverflow.com › questions › 66586316 › how-can-i-convert-a-python-binary-string-to-hex
How can I convert a python binary string to hex? - Stack Overflow
We on StackOverflow expect you ... ... In python, hex does not work like that. Try it like this: binary_str = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' print(binary_str.hex())...
🌐
GeeksforGeeks
geeksforgeeks.org › python-ways-to-convert-hex-into-binary
Python - Ways to convert hex into binary - GeeksforGeeks
February 20, 2025 - For example a = "1A3" we need to convert it to binary so that resultant output should be 110100011. We can convert hexadecimal to binary by first converting it to an integer using int() and then using the bin() function.
🌐
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.
🌐
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 - 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). The approach to convert a hexadecimal value into a binary value in Python is simple enough.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-hex
Python hex() | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.