0

I'm trying to translate a stream of 0, 1 to characters, without using other libraries,

for example 'Hello World':

0100100001000101010011000100110001001111001000000101011101001111010100100100110001000100

I found something like this:

def BinaryToString(binary):
    bingen = (binary[i:i+7] for i in range(0, len(binary), 7))
    return ''.join(chr(eval('0b'+n)) for n in bingen)

but when I'm trying to translate, this is the answer:

>>> BinaryToString("0100100001000101010011000100110001001111001000000101011101001111010100100100110001000100")
"$\x11)Db<@W'TID\x04"
>>> 
Dor Lugasi-Gal
  • 1,430
  • 13
  • 35

2 Answers2

1

That function is taking 7 binary digits at a time and converting them to a character. Change it to convert 8 digits at a time.

def BinaryToString(binary):
    bingen = (binary[i:i+8] for i in range(0, len(binary), 8))
    return ''.join(chr(eval('0b'+n)) for n in bingen)

This all depends on how your original text is encoded to begin with, but it works with the example you provided. (ASCII was originally defined using 7 bits. The extended ASCII table uses 8.)

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
1

int takes a second argument to specify the base, so you can just use something like int("00001110", 2) to get 14.

>>> binary = "0100100001000101010011000100110001001111001000000101011101001111010100100100110001000100"
>>> ''.join([chr(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8)])
'HELLO WORLD'
chepner
  • 497,756
  • 71
  • 530
  • 681