Python进制转换

一 内置函数

Python进制转换

  bin()、oct()、hex()的返回值均为字符串,且分别带有0b、0o、0x前缀。

实例 统计二进制数里1的个数

def countBits(n):
    return bin(n).count("1")
countBits(4)

二 format

In [54]: '{:b}'.format(17)
Out[54]: '10001'
In [55]: '{:d}'.format(17)
Out[55]: '17'
In [56]: '{:o}'.format(17)
Out[56]: '21'
In [57]: '{:x}'.format(17)
Out[57]: '11'

  实例 求两个二进制字符串的和 不能用内置函数

def toDecimal(num):
    return  sum( (b == '1')*2**i  for i,b in enumerate(num[::-1]))  
def add(a,b):
    return '{:b}'.format(toDecimal(a) + toDecimal(b))
add('111','10')

'1001' #这里没有前缀

此外format还有很多其他功能,控制精度,对齐等格式化输出

上面统计1的个数也可以写成

def countBits(n):
    return '{:b}'.format(n).count('1')