【解決方法】Python のバイナリ文字列変換で間違った値が返される


GeeksForGeeks のチュートリアルに従いました。これが私のコードです。

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)

このプログラムはこれを出力します:


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

Solution 1

These two lines are incorrect:

Python
for i in range(0, len(data), 7):
    temp_data = int(data[i:i + 7])

各バイナリ部分は 7 桁ではなく 8 桁なので、次のようになります。

Python
for i in range(0, len(data), 8):
    temp_data = int(data[i:i + 8])

解決策 2

それ以外の

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

使用

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

ASCII は 128 文字 (7 ビットに相当) を 256 ではなく 8 ビットで表します。

文字 – データ表現 – 高等計算科学改訂版 – BBC バイトサイズ[^]

テキストを 7 ビットのチャンクに分割すると、一度に 7 ビットずつ読み取る必要があり、8 ビットの場合はその逆になります。

コメント

タイトルとURLをコピーしました