【Python】十进制转二进制

手算十进制转二进制,即将十进制数除2取余,根据这个思想,设计以下算法。

base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]

def dec2bin(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 2)
        mid.append(base[rem])
    

    return ''.join([str(x) for x in mid[::-1]])

print(dec2bin('10'))

其中base为:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']

mid为:
['0', '1', '0', '1']

output:
1010

你可能感兴趣的:(学习)