Python program to convert binary to ASCII
In this article, we are going to see the conversion of Binary to ASCII in the Python programming language. There are multiple approaches by which this conversion can be performed that are illustrated below:
Method 1: By using binascii module
Binascii helps convert between binary and various ASCII-encoded binary representations.
b2a_uu() function: Here the “uu” stands for “UNIX-to-UNIX encoding” which takes care of the data conversion from strings to binary and ASCII values according to the specified program.
The b2a_uu() function is used to convert the specified binary string to its corresponding ASCII equivalent.
Parameter: This function accepts a single parameter which is illustrated below:
- Text: This is the specified binary string that is going to be converted into its ASCII equivalent.
Return Values: This function returns the ASCII equivalent.
Example: Convert binary to ASCII.
Method 2: Using Built-in Types.
Here we will use a built-in type to convert binary to ASCII value.
Firstly, call int(binary_sting, base) with the base as 2 indicating the binary string. and then call int.to_bytes(byte_number, byte_order) function, where byte_order is taken as “big” and byte_number is taken as the number of bytes that binary_int occupies to return an array of bytes. This byte_number can be found using the operation binary_int.bit_length() + 7 // 8. And then call array.decode operation to turn the array into ASCII text.
Example: Convert binary to ASCII
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course