Convert int to ASCII and back in Python Convert int to ASCII and back in Python python python

Convert int to ASCII and back in Python


ASCII to int:

ord('a')

gives 97

And back to a string:

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

gives '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 ncharsx = 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