码迷,mamicode.com
首页 > 编程语言 > 详细

Python进制转换

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

标签:精度   技术分享   format   rate   targe   技术   oct   enumerate   image   

一 内置函数

技术分享

  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进制转换

标签:精度   技术分享   format   rate   targe   技术   oct   enumerate   image   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!