Python program to convert ASCII to Binary - GeeksforGeeks (2024)

Last Updated : 08 Feb, 2024

Summarize

Comments

Improve

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)

Method #3 – using ord(), zfill() and bin() method –

In this approach we will simply use the ord() method alongside the bin() method to convert the string into binary. We will do it characterwise and later we will join it together

Step – 1 : Firstly we will define a function which takes the string as input.

Step – 2 : Then we will use the ord() and bin() method together to first convert the character into it’s ASCII value and then convert that ASCII into binary.

Step – 3: As the bin() method of Python converts into binary and starts the result with “0b” we will consider values starting after the”b”, generally the binary of any character is of length 8 (including the 0b part), so as we are omitting the 0b part we will use the zfill() method to make those results of length 8.

Step – 4 : As we are converting character by character the result will be a list in which each element will be the binary equivalent of each character. So to print them together we will use the join() method.

Below is the Implementation –

Python3

# Function to convert a string

# into it's equivalent Binary

def string_to_binary(st : str):

return [bin(ord(i))[2:].zfill(8) for i in st]

# This is an optional function

# this is to show that our result is correct

def binary_to_string(bits):

return ''.join([chr(int(i, 2)) for i in bits])

# Driver Code

st = "GFG"

# Storing the result in variable b

# Currently the result is in list format

b = string_to_binary(st)

# We are joining each element of the list

bt = "".join(b)

# Printing the final Result

print("Converting the String into Binary : ",bt)

# This section is just to verify

# the result we got is correct

s = binary_to_string(b)

# Printing the result

print("The string created from the binary parts : ",s)

Output

Converting the String into Binary : 010001110100011001000111The string created from the binary parts : GFG

Time Complexity – O(n) # n is the length of the string

Auxiliary Space – O(n) #n is the length of the list that will form



K

Kanchan_Ray

Python program to convert ASCII to Binary - GeeksforGeeks (1)

Improve

Next Article

Python program to convert binary to ASCII

Please Login to comment...

Python program to convert ASCII to Binary - GeeksforGeeks (2024)
Top Articles
Is It Worth Buying a House to Rent Out to My Parents?
Ultimate Guide to LinkedIn Outreach in 2024 - Clevenio
Menards Thermal Fuse
55Th And Kedzie Elite Staffing
Login Page
Gamevault Agent
Mountain Dew Bennington Pontoon
Greedfall Console Commands
Rondale Moore Or Gabe Davis
EY – все про компанію - Happy Monday
7.2: Introduction to the Endocrine System
2022 Apple Trade P36
THE 10 BEST River Retreats for 2024/2025
Obituary | Shawn Alexander | Russell Funeral Home, Inc.
Builders Best Do It Center
Used Drum Kits Ebay
Wilmot Science Training Program for Deaf High School Students Expands Across the U.S.
Truck Trader Pennsylvania
Connect U Of M Dearborn
Aldi Sign In Careers
Hellraiser III [1996] [R] - 5.8.6 | Parents' Guide & Review | Kids-In-Mind.com
Locate At&T Store Near Me
10-Day Weather Forecast for Santa Cruz, CA - The Weather Channel | weather.com
Army Oubs
Metro Pcs.near Me
Satisfactory: How to Make Efficient Factories (Tips, Tricks, & Strategies)
Robin D Bullock Family Photos
Heart Ring Worth Aj
Yugen Manga Jinx Cap 19
Hctc Speed Test
Urban Dictionary Fov
Makemv Splunk
Star Wars Armada Wikia
Generator Supercenter Heartland
Darknet Opsec Bible 2022
Etowah County Sheriff Dept
Cl Bellingham
Wo ein Pfand ist, ist auch Einweg
Cookie Clicker The Advanced Method
What to Do at The 2024 Charlotte International Arts Festival | Queen City Nerve
All Weapon Perks and Status Effects - Conan Exiles | Game...
Vagicaine Walgreens
Paperlessemployee/Dollartree
Product Test Drive: Garnier BB Cream vs. Garnier BB Cream For Combo/Oily Skin
M Life Insider
Jigidi Jigsaw Puzzles Free
Compete My Workforce
Hcs Smartfind
Syrie Funeral Home Obituary
Bellin Employee Portal
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 5305

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.