RF Coding Chronicles

Follow

RF Coding Chronicles

Follow
Convert any Text to Binary using Python

Convert any Text to Binary using Python

MD Fahad Islam's photo
MD Fahad Islam
ยทOct 30, 2021ยท

1 min read

Play this article

Introduction

In this tutorial, I will show you how to convert text to binary or binary to text. I will also show you how it works. Let's Start!

String To Binary

def str_to_binary(text):
    binary = ""
    for char in text:
        binary += format(ord(char), '08b')
    return binary

Describing code:

  • The function will take a plain text or sentence

  • Then loop over each character to convert to binary and add the binary code of every character to the binary variable

The format() method returns a formatted representation of the given value controlled by the format specifier. read more : format() in python

  • format(value, format-specifier) | in this case, this function takes per character's Unicode as value, and '08b' means 8-bit binary format specifier

  • ord() converts any character to its ASCII Unicode.

Conclusion

Sorry for any mistakes as it is my first blog. Thanks a lot. I hope you will find this helpful. I will try more to improve my content. See you in the future!๐Ÿ˜€

Github profile : RF Fahad Islam

ย 
Share this