首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python十进制转二进制,可指定位数

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

原创
作者头像
艳艳代码杂货店
修改2021-11-02 11:20:37
8370
修改2021-11-02 11:20:37
举报

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</pre> 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档