Sometimes we need to decode binary to know what it tells us or what it means. We know the computer can read binary but It’s very hard for a human to read binary. There are so many binary converters online. But it much more exciting to create it by ourselves. In this article, I will try to cover this topic.

Decode binary to text is pretty easy in Python. We are going to use some pythonic way to do this. So, we are going to decode this ‘ 01010000… 00100001’ binary to text. It’s the binary version of “Python is awesome!”.

First of all, we will store it in a variable called binary. and split the string using whitespace as a separator. Here every element in the list is a character including whitespace.

```binary = '01010000 01111001 01110100 01101000 01101111 01101110 00100000 01101001 01110011 00100000 01100001 01110111 01100101 01110011 01101111 01101101 01100101 00100001'

convert_to_list = binary.split(' ')```

After that, we have to convert each element of the list into it’s ASCII value and then convert the ASCII value with their associated character value. To do this we use map() function for iterate through each element. It’s a built python function and in this case, it takes two-parameter. First, a function to execute for each item and second are iterable.

```def convert_to_text(n):
return chr(int(n, 2))

converted = map(convert_to_text, convert_to_list)```

In the convert_to_text function, we use int() function to convert binary to ASCII and chr() function to convert ASCII to the character. In int() function, the second parameter 2 is defined as what number system it is. After that, join each element in a string.

`result = ''.join(converted)`

Below is the full code.

```binary = '01010000 01111001 01110100 01101000 01101111 01101110 00100000 01101001 01110011 00100000 01100001 01110111 01100101 01110011 01101111 01101101 01100101 00100001'

convert_to_list = binary.split(' ')

def convert_to_text(n):
return chr(int(n, 2))

converted = map(convert_to_text, convert_to_list)

result = ''.join(converted)
print(result) # Output = 'Python is awesome!'```

Happy Coding 🙂
Happy Learning 🙂

Published inPython