2023年1月4日 星期三

進位轉換

 def two2ten(a):

# a = '10101'

    b = [int(i) for i in a]

    # print(b)

    c = []

    s = 0

    k =len(a)-1

    for i in b:

        s = s + i*2**k

        k-=1

    return s


def ten2two(n):

# n = 18

    if n==0 :return '0'

    s = ''

    while n>=1:

        s = str(n%2) + s 

        n = n//2

    return s


for i in ['1','10','11','101','10111011']:

    print(f'{i} -> {two2ten(i)}')

for i in range(20):

    print(i,ten2two(i))