1. 程式人生 > 實用技巧 >二進位制、八進位制、十進位制、十六進位制之間的轉換!

二進位制、八進位制、十進位制、十六進位制之間的轉換!

進位制轉換圖:

自己實現的進位制轉換,供參考:

def to_bin(number):
    """ 十進位制轉換為二進位制 """
    bin_num = ''
    while number:
        bin_num += str(number % 2)
        number >>= 1
    bin_num = bin_num[::-1]
    '''
    補0:
    n = (8 - (len(bin_num) % 8))
    if n < 8:
        prefix = '0' * n
        bin_num = prefix + bin_num
    
''' return bin_num def to_oct(number): """ 十進位制轉換為八進位制 """ oct_num = '' while number: oct_num += str(number % 8) number >>= 3 return oct_num[::-1] def to_hex(number): """ 十進位制轉十六進位制 """ hex_num = '' while number: hex_num += str(number % 16) number
>>= 4 return hex_num[::-1] def to_dec(number, rule): """ 將進位制數按照進位制規則轉換為十進位制數 :param number: 進位制數 :param rule: 進位制 :return: 十進位制數 """ res = 0 num_list = list(number) lenth = len(num_list) for i in range(lenth): if num_list[i] != '0': res
+= int(num_list[i]) * rule ** (lenth - 1 - i) return res