在python转换为二进制整数 [英] Converting integer to binary in python

查看:335
本文介绍了在python转换为二进制整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为整数转换为二进制,我已经使用这个code:

 >>>箱(6)
0b110

和何时擦除'0B',我用这个:

 >>>槽(6)[2:]
110

我能做些什么,如果我想显示 6 00000110 而不是 110


解决方案

 >>> {0:08B}。格式(6)
00000110

只是为了解释格式化字符串的部分:


  • {} 放置一个变量为一个字符串

  • 0 需要在参数位置0
  • 变量
  • 添加了格式化选项,此变量(否则将重新present小数 6

  • 08 格式左侧
  • 来八位数零填充
  • B 数转换成其二进制重新presentation

In order to convert an integer to a binary, i have used this code :

>>> bin(6)  
'0b110'

and when to erase the '0b', i use this :

>>> bin(6)[2:]  
'110'

What can i do if i want to show 6 as 00000110 instead of 110?

解决方案

>>> '{0:08b}'.format(6)
00000110

Just to explain the parts of the formatting string:

  • {} places a variable into a string
  • 0 takes the variable at argument position 0
  • : adds formatting options for this variable (otherwise it would represent decimal 6)
  • 08 formats the number to eight digits zero-padded on the left
  • b converts the number to its binary representation

这篇关于在python转换为二进制整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆