to the ASCII text:
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
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) print(my_int) # 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:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.