首页 > 编程语言 > 详细

Python进制转换

时间:2016-11-01 13:59:38      阅读:180      评论:0      收藏:0      [点我收藏+]

一 内置函数

技术分享

  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‘)

Python进制转换

原文:http://www.cnblogs.com/zephyr-1/p/6018765.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!