How to Convert Binary String to and from Ascii Text in Python (2024)

In this tutorial, we will see How to convert any binary string to and from ASCII text in Python. ASCII stands for American Standard Code For Information Interchange. It is a standard 8-bit encoding format that assigns numerical values to other characters in a computer such as letters, punctuation marks, etc.

In Python, you can convert a binary string to ASCII text and vice versa using the built-in functions and methods. To convert a binary string to ASCII text, you can use the int function with base 2 to convert the binary string to an integer, followed by the chr function to convert the integer to its corresponding ASCII character. For example:

binary_string = '01101000 01100101 01101100 01101100 01101111'ascii_text = ''.join(chr(int(binary, 2)) for binary in binary_string.split())print(ascii_text)

Conversely, to convert ASCII text to a binary string, you can use the ord function to get the ASCII value of each character and then use the format function to convert the ASCII value to its binary representation. For example:

ascii_text = 'Hello'binary_string = ' '.join(format(ord(char), '08b') for char in ascii_text)print(binary_string)

What We'll Cover

Finding ASCII Value

The ASCII value of ‘K’ is 75. You can check the ASCII value of different characters by executing the code given below. It takes an input character from the user and displays its ASCII value using the ord() function.

# Program to find the ASCII value of the given characterchar = str(input("Enter any character: "))print("The ASCII value of '" + char + "' is", ord(char))
Enter any character: aThe ASCII value of 'a' is 97

The ord() function only works for a character. If you want to obtain the ASCII value of all characters in a string then use a for loop to access all elements one by one. Convert them into ascii using ord() function and append the value in another variable.

Computers store data in the form of binary numbers i.e. 1’s and 0’s. Suppose you want to perform some operations or manipulate a string that is stored in the computer memory. For this, you need to convert this binary string to ASCII value to retrieve the original string. This article discusses different ways to convert a binary string into ASCII value using Python language.

If you want to learn more about Python Programming, visitPython Programming Tutorials.

Converting binary string or text to ASCII using binascii module

Binascii module aids in the conversion of binary strings to their equivalent ASCII representation. First of all, import the library of binascii and then take a binary string as input from the user. You can also convert a string to binary representation by inserting “b” at the start of an input string. b2a.uu() is a binascii function that converts the binary string to ASCII representation.

import binascii# Initializing a binary stringText = b"This is my string"ASCII = binascii.b2a_uu(Text)# Getting the ASCII equivalentprint(ASCII)
b"15&AI<R!I<R!M>2!S=')I;F< \n"

Converting binary String to ASCII using int.to_ byte() function

The first step is to initialize a binary string using the int(binary_input, base) command. Pass the string of 0s and 1s in the first argument and the base of the number system in the second argument. Before moving towards coding, let’s first understand how a binary string composed of bits of 0s and 1s is converted into an ASCII value. You already know eight bits are equal to 1 byte. Suppose you have a binary string as shown below. In order to find the ASCII value, we first grouped 8 bits. A group of 8 bits represents 1 byte which represents 1 character.

How to Convert Binary String to and from Ascii Text in Python (1)

The first step is to find the number of bytes in a binary string which is done using (input_string.bit_length() +7) // 8 command. Here, input_string.bit_length() returns the total number of bits in an input string. After this, convert it into ASCII text using the decoder() function. The complete code is given below.

# Initialize a binary stringinput_string=int("0100100001100101011011000110110001101111", 2);#Obtain the total number of bytesTotal_bytes= (input_string.bit_length() +7) // 8#Convert these bits to bytesinput_array = input_string.to_bytes(Total_bytes, "big")#Convert the bytes to an ASCII value and display it on the output screenASCII_value=input_array.decode()print(ASCII_value)
Hello

Converting ASCII to Binary Text using Int.from_bytes() function

The above two methods were related to the conversion of binary to ASCII. In this method, we will learn to convert ASCII to Binary. For this, convert the string into an array using string.encode() function. Then call the function int.from_byte() to convert the array of bytes into a binary integer which is then passed to the bin() function to obtain a binary string of 0s and 1s.

input_array = "Hello".encode()binary_array= int.from_bytes(input_array, "big")output_string = bin(binary_array)print(output_string)
0b100100001100101011011000110110001101111

This tutorial is all about the conversion of binary from ASCII and vice versa. Similarly, you can also convert other number systems such as decimal numbers, and hexadecimal numbers into binary numbers and vice versa.

If you have any feedback about this article, do let us know. To learn more about Python language, visit this link.

Related Posts:

  • Extract text from PDF File using Python
  • How to read a binary file in python
  • Python File I/O: How to Open, Read, and Write to a…
  • how to convert a string to boolean in python
  • Convert a JSON String to a Dictionary in Python
  • How to Convert a String List into an Integer List in Python
How to Convert Binary String to and from Ascii Text in Python (2024)

FAQs

How to Convert Binary String to and from Ascii Text in Python? ›

Method 1: By using binascii module

How to convert binary string to ASCII? ›

Given a binary string str, the task is to find its equivalent ASCII (American Standard Code for Information Interchange) character string. Explanation: Dividing str into set of 8 bits as follows: 01100001 = 97, ASCII value of 97 is 'a'. 01100010 = 98, ASCII value of 98 is 'b'.

How do you convert ASCII to binary in Python? ›

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

How to convert binary into text in Python? ›

Method #1:

The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string. This ASCII code is then converted to string using chr() function.

How to convert string to ASCII value in Python? ›

Here's a sample code: string = "hello" ascii_values = [ord(char) for char in string] print(ascii_values) This will output: [104, 101, 108, 108, 111] So, basically, each number in above output corresponds to the ASCII value of the character in the string.

How to convert ASCII value to binary? ›

To manually convert an ASCII character to binary: Determine the character's ASCII decimal value. Convert the decimal value to binary by dividing it by two and noting the remainders until you get to zero.

How do you convert a number to an ASCII character in Python? ›

An Integer To Ascii Characters Using chr() Function

In this example, below code assigns the ASCII character representation of the integer value 72 to the variable `ascii_char` using the `chr()` function, and then prints the result with a label. In this case, the output will be “Using chr() Function: H”.

How to convert ASCII char to binary in Python? ›

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.

How to convert number to string by ASCII value? ›

Here's an example: int number = 65; // ASCII value for 'A' String asciiString = Character. toString((char) number); In this example, the int value 65 is cast to a char and then converted to a String using Character.

How to get the ASCII value of a string? ›

Here are few methods in different programming languages to print ASCII value of a given character : Python code using ord function : ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord('a') returns the integer 97.

How to convert letters to ASCII binary? ›

To manually convert an ASCII character to binary: Determine the character's ASCII decimal value. Convert the decimal value to binary by dividing it by two and noting the remainders until you get to zero.

What does 01001000 01100101 01101100 01101100 01101111 00100001 mean? ›

01001000 01100101 01101100 01101100 01101111 00100001

Those ones and zeros might not look like anything to you, but in binary code the numbers are actually saying “Hello!

How do I get the ASCII code of a string? ›

Here are few methods in different programming languages to print ASCII value of a given character : Python code using ord function : ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord('a') returns the integer 97.

Top Articles
What’s the Minimum Car Insurance I Need in California?
Comprehension Questions
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
From Algeria to Uzbekistan-These Are the Top Baby Names Around the World
Urinevlekken verwijderen: De meest effectieve methoden - Puurlv
Knaben Pirate Download
Rapv Springfield Ma
R/Altfeet
Shemal Cartoon
What Happened To Maxwell Laughlin
Cnnfn.com Markets
U/Apprenhensive_You8924
Belle Delphine Boobs
How to find cash from balance sheet?
Rondom Ajax: ME grijpt in tijdens protest Ajax-fans bij hoofdbureau politie
Petco Vet Clinic Appointment
Is A Daytona Faster Than A Scat Pack
Mail.zsthost Change Password
Https Paperlesspay Talx Com Boydgaming
Johnnie Walker Double Black Costco
Kcwi Tv Schedule
Puretalkusa.com/Amac
Aes Salt Lake City Showdown
Ac-15 Gungeon
Hampton University Ministers Conference Registration
2000 Ford F-150 for sale - Scottsdale, AZ - craigslist
Aes Salt Lake City Showdown
Does Royal Honey Work For Erectile Dysfunction - SCOBES-AR
Acuity Eye Group - La Quinta Photos
Autopsy, Grave Rating, and Corpse Guide in Graveyard Keeper
Luciipurrrr_
Suspect may have staked out Trump's golf course for 12 hours before the apparent assassination attempt
Goodwill Houston Select Stores Photos
KITCHENAID Tilt-Head Stand Mixer Set 4.8L (Blue) + Balmuda The Pot (White) 5KSM175PSEIC | 31.33% Off | Central Online
Aliciabibs
Trivago Myrtle Beach Hotels
Mixer grinder buying guide: Everything you need to know before choosing between a traditional and bullet mixer grinder
Captain Billy's Whiz Bang, Vol 1, No. 11, August, 1920&#10;America's Magazine of Wit, Humor and Filosophy
Urban Blight Crossword Clue
Engr 2300 Osu
Candise Yang Acupuncture
N33.Ultipro
Jigidi Free Jigsaw
Keci News
Leland Westerlund
Mit diesen geheimen Codes verständigen sich Crew-Mitglieder
Santa Ana Immigration Court Webex
BYU Football: Instant Observations From Blowout Win At Wyoming
Ippa 番号
Noaa Duluth Mn
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6101

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.