For ASCII characters in the range [ -~] on Python 2:

>>> import binascii
>>> bin(int(binascii.hexlify('hello'), 16))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> binascii.unhexlify('%x' % n)
'hello'

In Python 3.2+:

>>> bin(int.from_bytes('hello'.encode(), 'big'))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
'hello'

To support all Unicode characters in Python 3:

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0'

Here's single-source Python 2/3 compatible version:

import binascii

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return int2bytes(n).decode(encoding, errors)

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

Example

>>> text_to_bits('hello')
'0110100001100101011011000110110001101111'
>>> text_from_bits('110100001100101011011000110110001101111') == u'hello'
True
Answer from jfs on Stack Overflow
Top answer
1 of 8
182

For ASCII characters in the range [ -~] on Python 2:

>>> import binascii
>>> bin(int(binascii.hexlify('hello'), 16))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> binascii.unhexlify('%x' % n)
'hello'

In Python 3.2+:

>>> bin(int.from_bytes('hello'.encode(), 'big'))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
'hello'

To support all Unicode characters in Python 3:

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0'

Here's single-source Python 2/3 compatible version:

import binascii

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return int2bytes(n).decode(encoding, errors)

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

Example

>>> text_to_bits('hello')
'0110100001100101011011000110110001101111'
>>> text_from_bits('110100001100101011011000110110001101111') == u'hello'
True
2 of 8
34

Built-in only python

Here is a pure python method for simple strings, left here for posterity.

def string2bits(s=''):
    return [bin(ord(x))[2:].zfill(8) for x in s]

def bits2string(b=None):
    return ''.join([chr(int(x, 2)) for x in b])

s = 'Hello, World!'
b = string2bits(s)
s2 = bits2string(b)

print 'String:'
print s

print '\nList of Bits:'
for x in b:
    print x

print '\nString:'
print s2

String:
Hello, World!

List of Bits:
01001000
01100101
01101100
01101100
01101111
00101100
00100000
01010111
01101111
01110010
01101100
01100100
00100001

String:
Hello, World!
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ binascii.html
binascii โ€” Convert between binary and ASCII
Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by '`' instead of spaces. Changed in version 3.7: Added the backtick parameter. binascii.a2b_base64(string, /, *, strict_mode=False)ยถ
Discussions

Python Binary string to ASCII text - Stack Overflow
x = "01100001" How do i convert this string into ASCII Expected Result: print(x.somefunction()) Output: a More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 20, 2017
How to convert binary string to ascii string in python? - Stack Overflow
I've made a little python program that reads binary from a file and stores it to a text file, read the text file and store the binary. But, I can't get the binary to work... it reads the files like... More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 22, 2012
How to convert bytes to string in python?
Try this: line = ser.readline().strip() values = line.decode('ascii').split(',') a, b, c = [int(s) for s in values] The call to .strip() removes the trailing newline. The call .decode('ascii') converts the raw bytes to a string. .split(',') splits the string on commas. Finally the call [int(s) for s in value] is called a list comprehension, and produces a list of integers. More on reddit.com
๐ŸŒ r/Python
3
1
February 8, 2016
7-bit ASCII encoding in Python?
apply a bitmask of 0b1111111 or 127. that will zero out the 8th bit and keep the other 7 More on reddit.com
๐ŸŒ r/learnpython
7
0
March 9, 2020
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ help understanding converting binary to ascii
r/learnpython on Reddit: Help understanding converting binary to ascii
February 18, 2015 -

Note : This is a spoiler for the challenge in r/Dailyprogrammer this week so if you partake in that reddit beware!

Anyway, I was trying to work out how to change a string consisting of binary digits into a string of ascii characters. Some googling suggested a module that would work "binascii". Initially I was using the code binascii.b2a_uu(data) to convert, but this only works for 45 bytes or less. Some more googling led me to this code which works perfectly...

string = int("your binary here", 2) print binascii.unhexlify("%x" % string)

My problem is that I don't feel I understand why this works. Knowing that it does work is not good enough for me. I get that int("some binary",2) specifies an integer that is in base 2. What I don't understand is:

  1. Why does unhexlify turn binary into ascii? Hexadecmial doesn't come into it surely?

  2. What do the %x and % symbols mean? I think they must mean "everything"? But I am not sure.

Using this code with the following input:

"0110100001100101011011000110110001101111"

gives the output

"hello"

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-program-to-convert-binary-to-ascii
Python program to convert binary to ASCII - GeeksforGeeks
July 23, 2025 - ... # Python program to illustrate the # conversion of Binary to ASCII # Importing binascii module import binascii # Initializing a binary string Text = b"GFG is a CS Portal" # Calling the b2a_uu() function to # Convert the binary string to ...
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python binary string to ascii string โ€“ and vice versa
Python Binary String to ASCII String - and Vice Versa - Be on the Right Side of Change
December 5, 2022 - To convert the binary string to an (ASCII) string, use the Integer to_bytes() method after converting the binary string to a normal integer using int() with the base=2 argument.
๐ŸŒ
Entechin
entechin.com โ€บ home โ€บ how to convert binary string to and from ascii text in python
How to Convert Binary String to and from Ascii Text in Python
July 7, 2024 - Binascii module aids in the conversion of binary strings to their equivalent ASCII representation. First of all, import the library of binascii and then take a binary string as input from the user.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python_text_processing โ€บ python_conversion_binary_ascii.htm
Python Text Processing - Binary ASCII Conversion
The ASCII to binary and binary to ascii conversion is carried out by the in-built binascii module. It has a very straight forward usage with functions which take the input data and do the conversion. The below program shows the use of binascii module and its functions named b2a_uu and a2b_uu. The uu stands for "UNIX-to-UNIX encoding" which takes care of the data conversion from strings to binary and ascii values as required by the program.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-program-to-convert-ascii-to-binary
Python program to convert ASCII to Binary - GeeksforGeeks
Binary strings are joined with spaces. ... In this article, we are going to see the conversion of Binary to ASCII in the Python programming language.
Published: January 17, 2025
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-convert-string-to-binary
Python | Convert String to Binary - GeeksforGeeks
May 3, 2023 - The ord function converts the character to it's ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string. ... # Python3 code to demonstrate working of # Converting String to binary ...
๐ŸŒ
Compucademy
compucademy.net โ€บ ascii-to-binary-conversion-in-python
ASCII to Binary Conversion in Python โ€“ Compucademy
ascii_text = "I'm a smart coder" binary_string = ' '.join([f'{ord(char):08b}' for char in ascii_text]) print(binary_string) ... 01001001 00100111 01101101 00100000 01100001 00100000 01110011 01101101 01100001 01110010 01110100 01100011 01101111 01100100 01100101 01110010 ยท Here is sample of a table for converting from Binary to ASCII. Note: The table above provides only a few examples for brevity. A full table can be found here. Python offers powerful tools for converting data between binary and ASCII representations.
Price: $$
Address: United Kingdom
๐ŸŒ
Python
docs.python.org โ€บ 2.0 โ€บ lib โ€บ module-binascii.html
12.8 binascii -- Convert between binary and ASCII
Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char.
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ built-in-methods โ€บ convert-binary-string-to-normal-string
4 ways to Convert a Binary String to a Normal String - AskPython
April 23, 2023 - Now we have binary data divided into equal chunks, we now need to convert these chunks into decimal values with the help of the int() method along with a base 2. The decimal value is converted to the associated ASCII value with the help of chr(). ...
๐ŸŒ
The Web Dev
thewebdev.info โ€บ home โ€บ how to convert binary to ascii and vice versa with python?
How to convert binary to ASCII and vice versa with Python? - The Web Dev
October 21, 2021 - To convert binary to ASCII and vice versa with Python, we can use the binascii module. ... We call binascii.hexlify with b'hello' to convert the binary string to hex.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-convert-string-to-binary-in-python
How to convert string to binary in Python
... join the stringโ€™s individual ASCII values to a list (l) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101).
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ binascii.html
19.8. binascii โ€” Convert between binary and ASCII โ€” Python 3.4.10 documentation
June 16, 2019 - The binascii module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like uu, base64, or binhex instead. The binascii module contains low-level functions written in C for greater speed that are used by the higher-level modules. ... a2b_* functions accept Unicode strings containing only ASCII characters.