首页 > 解决方案 > 如何将字节数组转换为字符串?

问题描述

我刚刚完成了哈夫曼压缩算法的创建。我使用 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:无效的起始字节

标签: pythonarrayscompressionhuffman-code

解决方案


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

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

来源:将字节转换为字符串?


推荐阅读