📜  python convert base - Python 代码示例

📅  最后修改于: 2022-03-11 14:45:29.414000             🧑  作者: Mango

代码示例1
# 10 numbers + 26 upper case letters + 26 lower case letters + 128 printable ASCII characters = 190
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»â–‘▒▓│┤ÁÂÀ©â•£â•‘╗╝¢¥â”â””┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´≡±â€—¾¶§÷¸°¨·¹³²â– '
print('alphabet =', len(alphabet))

Number = '12020202002020202202020200101010110101010040404044040404004040404'


def base_encoder(number, base):
    if base > len(alphabet):
        print('base not supported')

    is_negative = number < 0
    number = abs(number)
    base_number = ''

    while number:
        number, i = divmod(number, base)
        base_number = alphabet[i] + base_number
    if is_negative:
        base_number = '-' + base_number

    return base_number


def base_decoder(number, base):
    if base > len(alphabet):
        print('base not supported')
    dict_of_alph = {d: i for i, d in enumerate(alphabet)}

    base_number = sum(dict_of_alph[h] * base ** pos for pos, h in enumerate(reversed(number)))

    return base_number


def base_changer(number, in_bace, out_bace):
    print(number, 'this is bace', in_bace)
    step_0 = base_decoder(number, in_bace)
    print(step_0, 'this is base 10')
    step_1 = base_encoder(step_0, out_bace)
    print(step_1, 'this is bace', out_bace)
    return step_1


step_2 = base_changer(Number, 5, 150)
step_3 = base_changer(step_2, 150, 5)