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)
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:
December 06, 2022 at 12:16AM Click here for more details...
=============================
The original post is available in Finxter by Chris
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================
Post a Comment