No title

Download script from .\base.py


import sys


argv = sys.argv
narg = len(argv)
if narg <= 3:
    print("")
    print("Usage: python {} val base_source base_target".format(argv[0]))
    print("")
    exit()
else:
    val = argv[1]
    base_source = int(argv[2])
    base_target = int(argv[3])


base_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
base_chars_dict = {
     "0": 0
    ,"1": 1
    ,"2": 2
    ,"3": 3
    ,"4": 4
    ,"5": 5
    ,"6": 6
    ,"7": 7
    ,"8": 8
    ,"9": 9
    ,"A": 10
    ,"B": 11
    ,"C": 12
    ,"D": 13
    ,"E": 14
    ,"F": 15
    ,"G": 16
    ,"H": 17
    ,"I": 18
    ,"J": 19
    ,"K": 20
    ,"L": 21
    ,"M": 22
    ,"N": 23
    ,"O": 24
    ,"P": 25
    ,"Q": 26
    ,"R": 27
    ,"S": 28
    ,"T": 29
    ,"U": 30
    ,"V": 31
    ,"W": 32
    ,"X": 33
    ,"Y": 34
    ,"Z": 35
    }

if base_source > len(base_chars_dict):
    print("")
    print("Error: base_source [{}] is too large.".format(base_source))
    print("")
    exit()
if base_target > len(base_chars_dict):
    print("")
    print("Error: base_target [{}] is too large.".format(base_target))
    print("")
    exit()

def value_base(char, b):
    return base_chars_dict[char]


print("")
print("Convert {} in base {} to base 10".format(val, base_source))

nstr = len(val)
v10 = 0
for i in range(nstr):
    idx = nstr - 1 - i
    v = value_base(val[idx], base_source)
    if v >= base_source:
        print("Error: The value at the {}-th digit {} is not compatible with base {}"
                .format(i, v, base_source))
        exit()

    dv = v * base_source**i
    v10 += dv
    print("{}-th digit = {}_{}:".format(i, v, base_source), end = '')
    print(" + {}^{} => + {:10}_10 => {:10}_10".format(v, base_source, dv, v10))


b10 = str(v10)
print("")
print("Convert {} in base 10 to base {}".format(b10, base_target))
vnext = v10
starget = ''
while 1:
    n = int(vnext / base_target)
    residue = vnext % base_target
    starget = base_chars[residue] + starget
    print("{:10} = {:10} * {:10} + {:2}:".format(vnext, n, base_target, residue), end = '')
    print(" base_{} => {}".format(base_target, starget))

    if n == 0:
        break

    vnext = n


print("")