Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to ASCII and back in Python

People also ask

How do I get the ASCII value of a number in Python?

Here we have used ord() function to convert a character to an integer (ASCII value). This function returns the Unicode code point of that character. Unicode is also an encoding technique that provides a unique number to a character.

How do you convert a number to ASCII?

You can use one of these methods to convert number to an ASCII / Unicode / UTF-16 character: You can use these methods convert the value of the specified 32-bit signed integer to its Unicode character: char c = (char)65; char c = Convert. ToChar(65);


ASCII to int:

ord('a')

gives 97

And back to a string:

  • in Python2: str(unichr(97))
  • in Python3: chr(97)

gives 'a'


>>> ord("a")
97
>>> chr(97)
'a'

If multiple characters are bound inside a single integer/long, as was my issue:

s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))

Yields '0123456789' and x = 227581098929683594426425L


What about BASE58 encoding the URL? Like for example flickr does.

# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' 
url = ''
while node_id >= 58:
    div, mod = divmod(node_id, 58)
    url = BASE58[mod] + url
    node_id = int(div)

return 'http://short.com/%s' % BASE58[node_id] + url

Turning that back into a number isn't a big deal either.