integer – Convert int to ASCII and back in Python

integer – 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

>>> ord(a)
97
>>> chr(97)
a

integer – Convert int to ASCII and back in Python

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

Leave a Reply

Your email address will not be published. Required fields are marked *