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

Moh*_*thi 6 python compression arrays huffman-code

我刚刚完成了霍夫曼压缩算法的创建。我使用 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()
Run Code Online (Sandbox Code Playgroud)

UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 中的字节 0x88:起始字节无效

Dor*_*rba 5

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

>>> print(bytearray("abcd", 'utf-8').decode())
abcd
Run Code Online (Sandbox Code Playgroud)

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