Converting integer to binary in python

2019-01-02 16:35发布

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?

8条回答
临风纵饮
2楼-- · 2019-01-02 17:15

eumiro's answer is better, however I'm just posting this for variety:

>>> "%08d" % int(bin(6)[2:])
00000110
查看更多
君临天下
3楼-- · 2019-01-02 17:23
>>> '{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
查看更多
看淡一切
4楼-- · 2019-01-02 17:23

Going Old School always works

def intoBinary(number):
binarynumber=""
if (number!=0):
    while (number>=1):
        if (number %2==0):
            binarynumber=binarynumber+"0"
            number=number/2
        else:
            binarynumber=binarynumber+"1"
            number=(number-1)/2

else:
    binarynumber="0"

return "".join(reversed(binarynumber))
查看更多
大哥的爱人
5楼-- · 2019-01-02 17:30

A bit twiddling method...

>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
'00000110'
>>> bin8(-3)
'11111101'
查看更多
千与千寻千般痛.
6楼-- · 2019-01-02 17:33

Just use the format function

format(6, "08b")

The general form is

format(<the_integer>, "<0><width_of_string><format_specifier>")
查看更多
人间绝色
7楼-- · 2019-01-02 17:34

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'

Shorter way via string interpolation (Python 3.6+):

>>> f'{6:08b}'
'00000110'
查看更多
登录 后发表回答