Ken
Ken

Reputation: 125

How to convert ASCII integers back to char within a loop?

I'm trying to convert multiple ASCII ints back to char and have it as a single string. I know how to do it one by one but I can't think of how to do it in a loop. This is the code I have to grab all the ascii ints in my ascii_message variable:

for c in ascii_message: 
    ascii_int = ord(c)

Thanks!

Upvotes: 0

Views: 1195

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55499

An efficient way to do this in Python 2 is to load the list into a bytearray object & then convert that to a string. Like this:

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

output

Some ASCII text.

Here's a variation that works correctly in both Python 2 & 3.

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

However, in Python 3, it'd be more usual to use an immutable bytes object rather than a mutable bytearray.

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

The reverse procedure can also be done efficiently with a bytearray in both Python 2 and 3.

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

output

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

If your "list of numbers" is actually a string, you can convert it to a proper list of integers like this.

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)

output

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

That looks the binary representation of a 14 bit number. So I guess there are further steps to solving this puzzle. Good luck!

Upvotes: 5

Related Questions