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?
CodePudding user response:
str_data='Hi'
binarystr = ''.join(format(ord(x),'b') for x in str_data)
String=''
for i in range(0,len(binarystr),7):
String =chr(int(binarystr[i:i 7],2))
print(String)
CodePudding user response:
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).
str_data_back = ''.join([chr(int(y, 2)) for y in [''.join(x) for x in zip(*[iter(binarystr)]*7)]])
and assert(str_data == str_data_back) will confirm
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('-')])
and assert(str_data == str_data_back) will confirm