python十进制转二进制,可指定位数
发布时间:2020-12-17 17:17:25 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 python十进制转二进制,可指定位数 # convert a decimal (denary,base 10) integer to a binary string (base 2)# tested with Python24 vegaseat 6/1
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考
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) # 22222111 # convert back to test it print int(Denary2Binary(255),2) # 255 print # this version formats the binary print int2bin(255,12) # 000022222111 # test it print int("000022222111",2) # 255 print # check the exceptions print Denary2Binary(0) print Denary2Binary(-5) # should give a ValueError 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 浅谈python中的__init__、__new__和__call__方法
- day58:Linux:BashShell&linux文件管理&linux文件下
- Python subprocess.check_call – 如何将stdout和stderr指向
- Python模块导入适用于一个文件,另一个文件失败
- django 安装redis及session使用redis存储
- 用Python的Flask框架结合MySQL写一个内存监控程序
- flask开发遇到 jinja2.exceptions.TemplateNotFound
- Python实现各种排序算法的代码示例总结
- Python – 如何解析并将JSON保存到MYSQL数据库
- python – XML-RPC – 无法编组递归字典