python十进制转二进制_python十进制转二进制,可指定位数

该博客介绍了两个Python函数,Denary2Binary和int2bin,用于将十进制整数转换为二进制字符串。Denary2Binary函数适用于任意正整数,而int2bin函数允许指定输出二进制字符串的位数。文章还包含了测试用例和异常处理,确保转换的正确性和格式化输出。
摘要由CSDN通过智能技术生成

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

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com

特别注意:本站所有转载文章言论不代表本站观点!

本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值