簡體   English   中英

如何在循環內將ASCII整數轉換回char?

[英]How to convert ASCII integers back to char within a loop?

我正在嘗試將多個ASCII整數轉換回char並將其作為單個字符串。 我知道如何一個接一個地做,但是我想不起來怎么做。 這是我必須在我的ascii_message變量中獲取所有ascii int的代碼:

for c in ascii_message: 
    ascii_int = ord(c)

謝謝!

在Python 2中執行此操作的有效方法是將列表加載到bytearray對象中,然后將其轉換為字符串。 像這樣:

ascii_message = [
    83, 111, 109, 101, 32, 65, 83, 67, 
    73, 73, 32, 116, 101, 120, 116, 46,
]

a = bytearray(ascii_message)
s = str(a)
print s

產量

Some ASCII text.

這是在Python 2和3中均可正常運行的變體。

a = bytearray(ascii_message)
s = a.decode('ASCII')

但是,在Python 3中,使用不可變bytes對象而不是可變的bytearray更為常見。

a = bytes(ascii_message)
s = a.decode('ASCII')

在Python 2和3中,使用bytearray也可以有效地完成反向過程。

s = 'Some ASCII text.'
a = list(bytearray(s.encode('ASCII')))
print(a)

產量

[83, 111, 109, 101, 32, 65, 83, 67, 73, 73, 32, 116, 101, 120, 116, 46]

如果您的“數字列表”實際上是一個字符串,則可以將其轉換為這樣的適當整數列表。

numbers = '48 98 49 48 49 49 48 48 48 49 48 49 48 49 48 48'
ascii_message = [int(u) for u in numbers.split()]
print(ascii_message)

a = bytearray(ascii_message)
s = a.decode('ASCII')
print(s)

產量

[48, 98, 49, 48, 49, 49, 48, 48, 48, 49, 48, 49, 48, 49, 48, 48]
0b10110001010100

看起來是14位數字的二進制表示。 因此,我想還有進一步的步驟可以解決這個難題。 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM