'How to convert a binary String to Original String

I have entered a string as:

str_data = 'Hi'

and then I converted the string to binary using format() as:

binarystr = ''.join(format(ord(x),'b') for x in str_data)

Now, I want to convert binary string back to my original string. Is it possible to do so in Python? If yes, then how to do that?

I know chr() gives character corresponding to the ascii value but how to use it with binary string?



Solution 1:[1]

2 approaches: assuming a fix length for your source string (7 binary entries) or allowing a flexible length

fix length (standard alphabet)

Here we assume that all the binary mapped from a chr entry have always 7 entries (quite standard).

split_source = [''.join(x) for x in zip(*[iter(binarystr)]*7)]

str_data_back = ''.join([chr(int(y, 2)) for y in split_source])

flexible length (more general, but maybe useless)

You need to add a separator when you create binarystr

E.g. binarystr = '-'.join(format(ord(x),'b') for x in str_data)

otherwise it is not possible to say what was from where.

By adding the -, you can reconstruct the str_data with:

str_data_back = ''.join([chr(int(x, 2)) for x in binarystr.split('-')])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1