Click here to Skip to main content
15,896,348 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I followed a tutorial on GeeksForGeeks, and this is my code:
Python
def StringToBinary(data: str):
    return str(''.join(format(ord(i), '08b') for i in data))

def BinaryToDecimal(data: str):
    data1 = data                //data1 is unused, no idea why they did this
    decimal, i, n = 0, 0, 0     //n is again unused
    while (data != 0):
        dec = data % 10
        decimal = decimal + dec * pow(2, i)
        data = data//10
        i += 1
    return (decimal)

def BinaryToString(data: str):
    str_data = " "
    for i in range(0, len(data), 7):
        temp_data = int(data[i:i + 7])
        decimal_data = BinaryToDecimal(temp_data)
        str_data = str_data + chr(decimal_data)
    return str_data

string0 = StringToBinary("Geeks")
string1 = BinaryToString(string0)
print(string0)
print(string1)

This program outputs this:
0100011101100101011001010110101101110011
 #Y,V[!!

When it's supposed to print out something like:
0100011101100101011001010110101101110011
 Geeks

Why is this happening? I write my code the same, just changing variable names.

What I have tried:

I have tried checking the tutorial multiple times and my code's functionality should be completely identical
Posted
Updated 25-Apr-23 6:27am

instead of
return str(''.join(format(ord(i), '08b') for i in data))

use
return str(''.join(format(ord(i), '07b') for i in data))


ASCII represents 128 characters (the equivalent of 7 bits) with 8 bits rather than 256.

Characters - Data representation - Higher Computing Science Revision - BBC Bitesize[^]

If you break up the text to 7bit chunks, you have to read it 7 bits at a time, and vice-versa with 8 bits.
 
Share this answer
 
v5
These two lines are incorrect:
Python
for i in range(0, len(data), 7):
    temp_data = int(data[i:i + 7])

Each binary part is 8 digits long not 7, so they should be:
Python
for i in range(0, len(data), 8):
    temp_data = int(data[i:i + 8])
 
Share this answer
 
Comments
Member 14769677 28-Jul-22 11:24am    
I though the 7 was wierd, i assumed it had something with indexing to do as it starts at 0 haha
Richard MacCutchan 28-Jul-22 11:53am    
Well it could be valid if the string to binary only used 7 digits.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900