[英]How to convert a byte array to string?
我剛剛創建了一個霍夫曼壓縮算法。 我使用 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:起始字節無效
您可以使用.decode('ascii')
(對於utf-8
留空)。
print(bytearray("abcd", 'utf-8').decode())
>>> abcd
來源: 將字節轉換為字符串?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.