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 module import binascii # Initializing a ASCII string Text = "21T9'(&ES(&$@0U,@4&]R=&%L" # Calling the a2b_uu() function to # Convert the ascii string to binary Binary = binascii.a2b_uu(Text) # Getting the Binary value print (Binary) |
Output:
b'GFG is a CS Portal'
Time Complexity: O(logn)
Space Complexity: O(n)
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 bytes byte_array = "GFG" .encode() # Converting the byte_array into a binary # integer binary_int = int .from_bytes(byte_array, "big" ) # Converting binary_int to a string of # binary characters binary_string = bin (binary_int) # Getting the converted binary characters print (binary_string) |
Output:
0b10001110100011001000111
The Time and Space Complexity of all the methods is :
Time Complexity: O(logn)
Space Complexity: O(n)
Please Login to comment...