﻿ python十进制转二进制，可指定位数_python_开心洋葱网
• 欢迎访问开心洋葱网站，在线教程，推荐使用最新版火狐浏览器和Chrome浏览器访问本网站，欢迎加入开心洋葱` QQ群`
• 为方便开心洋葱网用户，开心洋葱官网已经开启复制功能！
• 欢迎访问开心洋葱网站，手机也能访问哦~欢迎加入开心洋葱多维思维学习平台` QQ群`
• 如果您觉得本站非常有看点，那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~！
• 由于近期流量激增，小站的ECS没能经的起亲们的访问，本站依然没有盈利，如果各位看如果觉着文字不错，还请看官给小站打个赏~~~~~~~~~~~~~！

# python十进制转二进制，可指定位数

4099次浏览

python十进制二进制，可指定位数

```# convert a decimal (denary, base 10) integer to a binary string (base 2)
# tested with Python24   vegaseat    6/1/2005
def Denary2Binary(n):
'''convert denary integer n to binary string bStr'''
bStr = ''
if n < 0: raise ValueError, "must be a positive integer" if n == 0: return '0' while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr
def int2bin(n, count=24):
"""returns the binary of integer n, using count number of digits"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
# this test runs when used as a standalone program, but not as an imported module
# let's say you save this module as den2bin.py and use it in another program
# when you import den2bin the __name__ namespace would now be  den2bin  and the
# test would be ignored
if __name__ == '__main__':
print Denary2Binary(255)  # 11111111

# convert back to test it
print int(Denary2Binary(255), 2)  # 255

print

# this version formats the binary
print int2bin(255, 12)  # 000011111111
# test it
print int("000011111111", 2)  # 255

print
# check the exceptions
print Denary2Binary(0)
print Denary2Binary(-5)  # should give a ValueError
```