Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

5 Answers 5

up vote 60 down vote accepted
>>> '{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
share|improve this answer
5  
The first 0 means the 0th argument to format. After the colon is the formatting, the second 0 means zero fill to 8 spaces and b for binary –  jamylak May 2 '12 at 9:39
    
@Aif: Also, have a look at the standard documentation docs.python.org/library/… –  pepr May 2 '12 at 10:27
4  
This can be simplified with the format() function: format(6, '08b'); the function takes a value (what the {..} slot applies to) and a formatting specification (whatever you would put after the : in the formatting string). –  Martijn Pieters Sep 11 '13 at 17:33
    
'{0:08b}'.format(-6) -> '-0000110'. what if you don't want a sign? struct? -6%256? –  naxa Jun 23 at 11:17

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'
share|improve this answer
    
Note that this solution is faster than the accepted one. Which solution is more clear (or, dare I say it, Pythonic) is probably a matter of personal taste. –  AirThomas Feb 21 at 18:04

A bit twiddling method...

>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
>>> '00000110'
share|improve this answer

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

>>> "%08d" % int(bin(6)[2:])
00000110
share|improve this answer

.. or if you're not sure it should always be 8 digits, you can pass it as a parameter:

>>> '%0*d' % (8, int(bin(6)[2:]))
'00000110'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.