Python Binary String to ASCII String – and Vice Versa : Chris

Python Binary String to ASCII String – and Vice Versa
by: Chris
blow post content copied from  Finxter
click here to view original post


5/5 - (1 vote)

Problem Formulation

In this article, you’ll learn how to convert binary string (values) to an ASCII string in Python.

For example, you may want to convert the binary string:

0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100

to the ASCII text:

hello world

Using a simple Python script!

💬 Question: How would we write Python code to perform the binary to ASCII conversion and vice versa?

Solution: Integer to_bytes() and from_bytes()

To convert the binary string to an (ASCII) string, use the Integer to_bytes() method after converting the binary string to a normal integer using int() with the base=2 argument.

def bin_to_str(x):
    ''' Converts a Binary String to an (ASCII) string'''
    my_int = my_int = int(my_bin, base=2)
    my_str = my_int.to_bytes((my_int.bit_length() + 7)//8, 'big').decode()
    return my_str

my_bin = '0b0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'

my_int = bin_to_str(my_bin)
print(my_int)
# hello world

To convert the (ASCII) string back to a binary string, use the the Integer from_bytes() method on the encoded string.

def str_to_bin(x):
    ''' Converts an ASCII string to a binary string'''
    return bin(int.from_bytes(x.encode(), 'big'))


print(str_to_bin('hello world'))
# 0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100

Thanks for reading this short tutorial. ♥

To keep learning, feel free to dive deeper into this conversion topic here and download our cheat sheets here:


December 06, 2022 at 12:16AM
Click here for more details...

=============================
The original post is available in Finxter by Chris
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce