我刚刚完成了一个哈夫曼压缩算法。我使用bytearray()将压缩后的文本从字符串转换为字节数组。我正在尝试解压我的哈夫曼算法。我唯一的担忧是我无法将我的字节数组转换回字符串。是否有任何内置函数可用于将我的字节数组(具有变量)转换回字符串?如果没有,是否有更好的方法将我的压缩字符串转换为其他格式?我尝试使用byte_array.decode(),但我得到了这个结果:
print("Index: ", Index) # The Index
# Subsituting text to our compressed index
for x in range(len(TextTest)):
TextTest[x]=Index[TextTest[x]]
NewText=''.join(TextTest)
# print(NewText)
# NewText=int(NewText)
byte_array = bytearray() # Converts the compressed string text to bytes
for i in range(0, len(NewText), 8):
byte_array.append(int(NewText[i:i + 8], 2))
NewSize = ("Compressed file Size:",sys.getsizeof(byte_array),'bytes')
print(byte_array)
print(byte_array)
print(NewSize)
x=bytes(byte_array)
x.decode()
UnicodeDecodeError: 'utf-8'编解码器无法解码位置0处的字节0x88:起始字节无效
byte_array.decode('ascii')
。如果您省略解码参数,则默认为“utf-8”。 - martineau'hex'
可能很好用。您也可以使用'latin1'
,它将代码点0-255映射到字节0x0-0xff。 这样做将允许您稍后通过使用the_string.encode('latin1')
将结果转换回字节。 我是在这个答案中第一次听说这个方法(用于解决不同问题)。 - martineau