Skip to content

Instantly share code, notes, and snippets.

@skorokithakis
Created August 17, 2015 14:40
Show Gist options
  • Save skorokithakis/22b4b7d3a2a6944012ff to your computer and use it in GitHub Desktop.
Save skorokithakis/22b4b7d3a2a6944012ff to your computer and use it in GitHub Desktop.
String to int and back.
import math
def string_to_int(string):
"""Convert a string to the equivalent integer."""
# For each character, convert to an integer, convert that to hex,
# remove the first two chars ("0x") and left-pad with a zero.
hexchars = [hex(ord(x))[2:].rjust(2, "0") for x in string]
return int("".join(hexchars), 16)
def int_to_string(integer):
"""Convert an integer back to the equivalent string."""
hexstring = hex(integer)[2:].rstrip("L")
# Pad the hexstring with zeros to the left to get an even
# number of digits.
padded = hexstring.rjust(int(math.ceil(len(hexstring) / 2.0) * 2), "0")
stringlist = []
for counter in range(0, len(padded), 2):
# Convert every pair of two hex digits into a char.
charpair = padded[counter:counter + 2]
char = chr(int("0x" + charpair, 16))
stringlist.append(char)
return "".join(stringlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment