Welcome, guest | Sign In | My Account | Store | Cart

This code enable decimal base conversion according map length and a different char set.

Example:

  • map = ['0','1'] base 2 10 -> 1010
  • map = ['a','b'] base 2 10 -> baba
  • map = ['a','b','c','d','e','f','g','h','i','j','k','l'] base 12 10 -> k
  • map = ['a','b','c','d','e','f','g','h','i','j','k','l'] base 12 100 -> ie

this simple method can be used in web sites to hide a well known decimal sequence like user ids.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Deveploed by Mark Zitnik

# selected map can be change scrambled
map = ['a','b','c','d','e','f','g','h','i','j','k','l','1','H']

map_dict = {}
base = len(map)

# create a bi-directional dict
for item in range(base):
    map_dict[item] = map[item]
    map_dict[map[item]] = item

def i_to_map_base(num):
    if num == 0: return map_dict[0]
    base_str = []
    while num > 0:
        base_str.append(map_dict[ num % base ])
        num = num / base
    base_str.reverse()
    return ''.join(base_str)

def map_base_to_i(str):
    x = [a for a in str]
    x.reverse()
    value = 0
    for i in range(len(x)):
        item = x[i]
        value += (map_dict[item] * pow(base,i))
    return value

# test code
for i in range(1000):
    str = i_to_map_base(i)
    val = map_base_to_i(str)
    print 'i[%s] : [%s:%s]' % (i , str , val)
Created by Mark Zitnik on Wed, 20 Aug 2008 (MIT)
Python recipes (4591)
Mark Zitnik's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks