Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting alphanumeric string to int and vice versa in python

Tags:

python

I am trying to convert alphanumeric string with maximum length of 40 characters to an integer as small as possible so that we can easily save and retrieve from database. I am not aware if there is any python method existing for it or any simple algorithms we can use. To be specific my string will have only characters 0-9 and a-g. So kindly help with any suggestions on how we can uniquely convert from string to int and vice versa. I am using Python 2.7 on Cent os 6.5

like image 945
RAFIQ Avatar asked Dec 11 '22 00:12

RAFIQ


1 Answers

This is not that difficult:

def str2int(s, chars):
    i = 0
    for c in reversed(s):
        i *= len(chars)
        i += chars.index(c)
    return i

def int2str(i, chars):
    s = ""
    while i:
        s += chars[i % len(chars)]
        i //= len(chars)
    return s

Example:

>>> chars = "".join(str(n) for n in range(10)) + "abcdefg"
>>> str2int("0235abg02", chars)
14354195089
>>> int2str(_, chars)
'0235abg02'

Basically if you want to encode n characters into an integer you interpret it as base-n.

like image 76
orlp Avatar answered Dec 13 '22 14:12

orlp