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

猜你喜欢

转载自blog.csdn.net/qq_31362767/article/details/85928058