Python Binary String to ASCII String – and Vice Versa

4.3/5 - (3 votes)

Problem Formulation

In this article, you’ll learn how to convert binary string (values) to an ASCII string in Python.

For example, you may want to convert the binary string:


to the ASCII text:

hello world

Using a simple Python script!

πŸ’¬ Question: How would we write Python code to perform the binary to ASCII conversion and vice versa?

Solution: Integer to_bytes() and from_bytes()

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.

def bin_to_str(x):
    ''' Converts a Binary String to an (ASCII) string'''
    my_int = my_int = int(my_bin, base=2)
    my_str = my_int.to_bytes((my_int.bit_length() + 7)//8, 'big').decode()
    return my_str

my_bin = '0b0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'

my_int = bin_to_str(my_bin)
# hello world

To convert the (ASCII) string back to a binary string, use the the Integer from_bytes() method on the encoded string.

def str_to_bin(x):
    ''' Converts an ASCII string to a binary string'''
    return bin(int.from_bytes(x.encode(), 'big'))

print(str_to_bin('hello world'))
# 0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100

Thanks for reading this short tutorial. β™₯️

To keep learning, feel free to dive deeper into this conversion topic here and download our cheat sheets here: