Skip to content

Instantly share code, notes, and snippets.

@bcachet
Last active August 29, 2015 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcachet/55299 to your computer and use it in GitHub Desktop.
Save bcachet/55299 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def convert_base(value, base_k, base_n):
"""
Convert value from base K to base N
>>> convert_base('5', BASE10, BASE2)
101
>>> convert_base('10', BASE10, BASE2)
1010
>>> convert_base('33', BASE4, BASE8)
17
"""
num = express_value_in_base10(value, base_k)
return express_base10_value_in_base(num, base_n)
def express_value_in_base10(value, base):
"""
>>> express_value_in_base10('100', BASE10)
100
>>> express_value_in_base10('100', BASE2)
4
>>> express_value_in_base10('220', BASE3)
24
"""
polynoms = get_nb_polynoms_for_base(base, len(value))
return sum(map(lambda x: base.find(value[x])*polynoms[x], range(len(value))))
def express_base10_value_in_base(value, base):
"""
>>> express_base10_value_in_base(24, BASE3)
220
>>> express_base10_value_in_base(24, BASE8)
30
>>> express_base10_value_in_base(24, BASE10)
24
>>> express_base10_value_in_base(24, BASE20)
14
"""
tar = len(base)
res = ""
k = value
while k != 0:
k, l = k / tar, k % tar
res = base[l] + res
return int(res)
def get_nb_polynoms_for_base(base, nb):
"""
>>> get_nb_polynoms_for_base(BASE2, 4)
[8, 4, 2, 1]
>>> get_nb_polynoms_for_base(BASE3, 5)
[81, 27, 9, 3, 1]
"""
return map(lambda x: len(base)**(nb-x-1), range(nb))
def int_to_str(x):
"""
>>> int_to_str(9)
'9'
>>> int_to_str(16)
'G'
>>> int_to_str(32)
'W'
"""
return str(x) if x < 10 else chr(55 + x)
def base_as_str(base):
"""
>>> base_as_str(20)
'0123456789ABCDEFGHIJ'
>>> base_as_str(30)
'0123456789ABCDEFGHIJKLMNOPQRST'
"""
return base if isinstance(base, str) else ''.join(map(int_to_str, range(base)))
BASE10 = base_as_str(10)
BASE2 = base_as_str(2)
BASE3 = base_as_str(3)
BASE4 = base_as_str(4)
BASE8 = base_as_str(8)
BASE12 = base_as_str(12)
BASE20 = base_as_str(20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment