1s和0s字符串转换为二进制并再次字符串

时间:2019-03-13 09:25:16

标签: python-3.x encryption binary huffman-code

文本将转换为1和0的字符串,然后转换为二进制。从二进制我想能够再次读取它,但是输出是不同的。我认为问题出在二进制读取,而idk到底在哪里

import io
mytext = 'La tortilla de patatas siempre es redonda'
mylist = [('a', '101'), (' ', '110'), ('t', '010'), ('e', '011'), ('o', '0000'), ('r', '1000'), ('i', '0001'), ('d', '1001'), ('s', '1110'), ('L', '00110'), ('l', '11110'), ('p', '11111'), ('m', '00111'), ('n', '00100'), ('.', '00101')]
mydict = {k:v for (k,v) in mylist}
invdict = {v:k for (k,v) in mylist}
ciphtext = ''
newstr = ''
f = io.BytesIO()

for char in mytext:
    ciphtext += mydict[char]    
for i in range(0,len(ciphtext),8):
    f.write(bytes(chr(int(ciphtext[i:i+8],2)),'utf-8'))

f.seek(0)
for x in f.read():
    chain = bin(x)[2:] #cuts the '0b' part from a binary
    long = len(chain)
    if long == 8:
        newstr += chain
    else:
        newstr += '0'*(8-long)+chain #sets length to 8, bc for strings 01 != 001

print(ciphtext)
print(newstr)

为什么输出不同?我该如何解决?

0 个答案:

没有答案