1. 程式人生 > >python 中的進位制轉換 整理

python 中的進位制轉換 整理

工作中經常需要用到進位制轉換, 一直對這方面有一些模糊, 終於有時間把這方面整理一下了.
常用的進位制: 二進位制bin(), 八進位制oct(), 十進位制int(), 十六進位制hex()
下面我採用python3.6中的原始碼進行解釋, 來自python中的builtins.py

bin(x) 將一個整型數字轉換為二進位制字串

def bin(*args, **kwargs):  # NOTE: unreliably restored from __doc__ 
    """
    Return the binary representation of an integer.
    
       >>> bin(2796202)
       '0b1010101010101010101010'
    """
    pass

oct() 將一個整型數字轉換為一個八進位制字串

def oct(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    Return the octal representation of an integer.
    
       >>> oct(342391)
       '0o1234567'
    """
    pass

int() 將一個數字或者字串轉換為一個整型數字

    def __init__(self, x, base=10): # known special case of int.__init__
        """
        int(x=0) -> integer
        int(x, base=10) -> integer
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is a number, return x.__int__().  For floating point
        numbers, this truncates towards zero.
        
        If x is not a number or if base is given, then x must be a string,
        bytes, or bytearray instance representing an integer literal in the
        given base.  The literal can be preceded by '+' or '-' and be surrounded
        by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
        Base 0 means to interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        4
        # (copied from class doc)
        """
        pass

hex() 將一個整型數字轉換為一個十六進位制字串

def hex(*args, **kwargs):  # NOTE: unreliably restored from __doc__ 
    """
    Return the hexadecimal representation of an integer.
    
       >>> hex(12648430)
       '0xc0ffee'
    """
    pass

下面是一個不同進位制之間的相互轉換:

在這裡插入圖片描述
要注意的是內建的bin() oct() hex() 的返回值均為 字串的形式, 而且前面分別帶有0b 0o 0x 的字首;
示例如下:

>>> bin(15)
'0b1111'
>>> bin(2)
'0b10'
>>> oct(16)
'0o20'
>>> oct(64)
'0o100'
>>> hex(16)
'0x10'
>>> hex(256)
'0x100'

實際工作中我們可能需要自己寫進位制轉換, 因為自帶的返回值含有字首;

import os, sys
baseNum  = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E']  
# baseNum = [str(x) for x in range(1,10)] + [chr(x) for x in range(ord('A'), ord("F")) ]
# 二進位制轉為 十進位制
def bin2dec(strNum):
    return str(int(strNum,2))
print(bin2dec("11"))    #  3

# 八進位制轉為十進位制
def  oct2dec(strNum):
    return str(int(strNum,8))
print(oct2dec('11'))    # 9

# 十六進位制轉為十進位制
def  hex2dec(strNum):
    return str(int(strNum,16))
print(hex2dec('11'))    #  17
# 十進位制轉為二進位制
def dec2bin(strNum):
    num = int(strNum)
    bitList = []
    while num != 0:
        num, res = divmod(num,2)
        bitList.append(base[res])
    return ''.join([str(i) for i in bitList][::-1])
print(dec2bin("15"))
# 八進位制 和 十六進位制轉二進位制, 可以採用先轉為十進位制, 後再轉為二進位制
# 同理:
# 十進位制轉為八進位制
def dec2oct(strNum):
    num = int(strNum)
    bitList = []
    while num != 0:
        num, res = divmod(num,8)
        bitList.append(base[res])
    return ''.join([str(i) for i in bitList][::-1])
print(dec2oct("16"))

# 十進位制轉為十六進位制, 只要將上面程式碼中的 divmod(num,8) 改為 divmod(num,16)

進位制轉換, 如果直接轉一次不能完成的話, 那就先轉成其他進位制, 間接地轉.

參考部落格: https://www.cnblogs.com/jsplyy/p/5636246.html