Created
August 17, 2015 14:40
-
-
Save skorokithakis/22b4b7d3a2a6944012ff to your computer and use it in GitHub Desktop.
String to int and back.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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