There was little buggy version of Python base conversion around, so here quick hack for my own program, including test with random numbers to verify it.
Base conversion program
# -*- coding: cp1252 -*-
from random import randint
symbols = '0123456789abcdefghijklmnopqrstuvwxyzåäö'
symbol_values = dict(reversed(v) for v in enumerate(symbols))
def int_to_base(number, base):
if base > len(symbols) or base < 2:
raise ValueError('Invalid base %i' % base)
s = ''
if number < 0:
number, neg = -number, True
else:
neg = False
while number:
number, this = divmod(number, base)
s = symbols[this] + s
return (neg * '-' ) + s
def value_in_base(string, base):
minus = string.lstrip().startswith('-')
v = sum(symbol_values[sym] * base ** power
for power, sym in enumerate(reversed(string.strip(' -'))))
return -v if minus else v
num_check = 100
for count in range(num_check):
num, b = randint(-100000, 10000), randint(2,len(symbols))
print('Original %i' % num)
v = int_to_base(num, b)
print('%s base %i' % (v, b))
print(value_in_base(v, b))
if b < 37:
print('check: %s\n' % int(v, b))
assert int(v, b) == num
TrustyTony 888 pyMod Team Colleague Featured Poster
TrustyTony 888 pyMod Team Colleague Featured Poster
TrustyTony 888 pyMod Team Colleague Featured Poster
yuvalm2 0 Newbie Poster
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.