Python program to convert ASCII to Binary
In this article, we are going to discuss the conversion of ASCII to Binary in the Python programming language.
Method 1: Using binascii module
Binascii helps convert between binary and various ASCII-encoded binary representations.
a2b_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 a2b_uu() function is used to convert the specified ASCII format to its corresponding binary equivalent.
Syntax: a2b_uu(Text)
Parameter: This function accepts a single parameter which is illustrated below:
- Text: This is the specified ASCII string that is going to be converted into its binary equivalent.
Return Values: This function returns the binary equivalent.
Example: Convert ASCII to binary using Python
Python3
# Python program to illustrate the# conversion of ASCII to Binary # Importing binascii moduleimport binascii # Initializing a ASCII stringText = "21T9'(&ES;(&$@0U,@4&]R=&%L" # Calling the a2b_uu() function to# Convert the ascii string to binaryBinary = binascii.a2b_uu(Text) # Getting the Binary valueprint(Binary) |
Output:
b'GFG is a CS Portal'
Method 2: Using Built-in Types
Firstly, call string.encode() function to turn the specified string into an array of bytes and then call int.from_bytes(byte_array, byte_order) with byte_order as “big” to convert the byte_array into a binary integer. Finally, call bin(binary_int) to convert binary_int to a string of binary characters.
Example: Convert ASCII to binary using Python
Python3
# Python program to illustrate the# conversion of ASCII to Binary # Calling string.encode() function to# turn the specified string into an array# of bytesbyte_array = "GFG".encode() # Converting the byte_array into a binary # integerbinary_int = int.from_bytes(byte_array, "big") # Converting binary_int to a string of # binary charactersbinary_string = bin(binary_int) # Getting the converted binary charactersprint(binary_string) |
Output:
0b10001110100011001000111



