# Tips on how to Binary to Textual content (ASCII) Conversion in Python

0
8

## The problem#

Write a perform that takes in a binary string and returns the equal decoded textual content (the textual content is ASCII encoded).

Every 8 bits on the binary string symbolize 1 character on the ASCII desk.

The enter string will at all times be a sound binary string.

Characters could be within the vary from “00000000” to “11111111” (inclusive)

Word: Within the case of an empty binary string your perform ought to return an empty string.

## The answer in Python code#

Choice 1:

``````def binary_to_string(binary):
return "".be a part of(chr(int(binary[i:i+8],2)) for i in vary(0,len(binary),8))
``````

Choice 2:

``````def binary_to_string(binary):
consequence = ""

whereas binary:
consequence += chr(int(binary[:8], 2))
binary = binary[8:]

return consequence
``````

Choice 3:

``````import re

def binary_to_string(binary):
return re.sub(r'.'*8, lambda e: chr(int(e.group(), 2)), binary)
``````

## Check instances to validate our resolution#

``````import random

check.assert_equals(binary_to_string(''), '', 'Should deal with empty string')
check.assert_equals(binary_to_string('0100100001100101011011000110110001101111'), 'Hi there', 'Should deal with fundamental works')
check.assert_equals(binary_to_string('00110001001100000011000100110001'), '1011', 'Should deal with numeric characters')
check.assert_equals(binary_to_string('0101001101110000011000010111001001101011011100110010000001100110011011000110010101110111001011100010111000100000011001010110110101101111011101000110100101101111011011100111001100100000011100100110000101101110001000000110100001101001011001110110100000100001'), 'Sparks flew.. feelings ran excessive!', 'Should deal with particular charaters')
check.assert_equals(binary_to_string('0010000101000000001000110010010000100101010111100010011000101010001010000010100101010001010101110100010101110010011101000111100101010101010010010100111101001100011001000110011001100111011000100110001001101000011011100110110101001001010010110100001001001010010010110100100001001001010101010100111100101000001111110011111000111111001111000111111001111110011111100111111001111110001010010010100000101010001001100010010101011110001110010011100000110111001100010011001100101111001011010010111100101010001011010010101000101111'), '[email protected]#\$%^&*()QWErtyUIOLdfgbbhnmIKBJKHIUO(?>?<~~~~~)(*&%^98713/-/*-*/', 'Should deal with particular charaters')

# Should deal with random string
random_string = ''.be a part of(c
for _ in vary(12)
for c in random.selection('qwertyuiopasdfghjklzxcvbnm0123456789'))
random_string_binary = ''.be a part of('{:08b}'.format(ord(c)) for c in random_string)
check.assert_equals(binary_to_string(random_string_binary), random_string, 'Should deal with random string')
``````