大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全家桶1年46,售后保障稳定
# 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
# this version formats the binary
print int2bin(255, 12) # 000011111111
# test it
print int(“000011111111”, 2) # 255
# check the exceptions
print Denary2Binary(0)
print Denary2Binary(-5) # should give a ValueError
开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明python十进制转二进制,可指定位数!
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/219166.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...