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)