python十进制转二进制,可指定位数
- 作者: 我就是我_不一样的水果
- 来源: 51数据库
- 2022-08-12
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
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
