如何将字节数组转换为字符串?

时间:2018-11-21 06:45:52

标签: python arrays compression huffman-code bytestring

我刚刚完成了霍夫曼压缩算法的创建。我使用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

1 个答案:

答案 0 :(得分:2)

您可以使用.decode('ascii')(为utf-8留空)。

print(bytearray("abcd", 'utf-8').decode())
>>> abcd

来源:Convert bytes to a string?

相关问题