297

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 show6 as00000110 instead of110?

Peter Mortensen's user avatar
Peter Mortensen
31.4k22 gold badges110 silver badges134 bronze badges
askedMay 2, 2012 at 9:31
Smith's user avatar
1

17 Answers17

512
>>> '{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 decimal6)
  • 08 formats the number to eight digits zero-padded on the left
  • b converts the number to its binary representation

If you're using a version of Python 3.6 or above, you can also use f-strings:

>>> f'{6:08b}''00000110'
TrebledJ's user avatar
TrebledJ
9,0237 gold badges28 silver badges50 bronze badges
answeredMay 2, 2012 at 9:32
eumiro's user avatar
Sign up to request clarification or add additional context in comments.

7 Comments

The first0 means the0th argument toformat. After the colon is the formatting, the second0 means zero fill to 8 spaces andb for binary
@Aif: Also, have a look at the standard documentationdocs.python.org/library/…
This can be simplified with theformat()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).
'{0:08b}'.format(-6) ->'-0000110'. what if you don't want a sign?struct?-6%256?
@AK47 Yes, since Pythoon 2.6 you can write int constants in binary form with 0b or 0B prefix:0b00000110
|
138

Just another idea:

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

Shorter way viastring interpolation (Python 3.6+):

>>> f'{6:08b}''00000110'
answeredMay 2, 2012 at 9:37
mshsayem's user avatar

3 Comments

Note that this solution isfaster than the accepted one. Which solution is more clear (or, dare I say it, Pythonic) is probably a matter of personal taste.
I'm still learning the essence of pythonicity, but this is clearly much more versatile. I was initially excited to see the accepted solution with its elegant explanation, but alarmed that the object being called on to do the methods was written as a single string with all specifications built in, eliminating the involvement of variables in such things as the desired length of the bitstring. This solves that completely, and is so intuitive (at least for Python 2) that there's no need to explain each character!
Does not work for negative integerbin(-6)[2:].zfill(8) reads as'0000b110'
30

Just use the format function

format(6, "08b")

The general form is

format(<the_integer>, "<0><width_of_string><format_specifier>")
answeredApr 7, 2016 at 20:16
theOne's user avatar

1 Comment

Yes, I like this one, it's simple and one of the fastest :-)1000000 loops, best of 3: 556 ns per loop
26

A bit twiddling method...

>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )>>> bin8(6)'00000110'>>> bin8(-3)'11111101'
marbel82's user avatar
marbel82
9481 gold badge19 silver badges41 bronze badges
answeredMay 2, 2012 at 10:07
sobel's user avatar

4 Comments

Nice method. But I couldn't understand what this part of your code is doing: str((x >> i) & 1)
@Gregory: it shifts the bits inx to the right and ANDs it with1, effectively extracting one bit (0 or 1) at a time.
Very nice! As an observation,reversed could be removed by usingrange(7,-1,-1); albeit more ‘pure’, but perhaps less readable/intuitive.
This is the only answer that supports negative numbers (which, since Python stores them in 2's complement, are output in 2's complement format with this method).
13

numpy.binary_repr(num, width=None) has a magic width argument

Relevant examples from the documentation linked above:

>>> np.binary_repr(3, width=4)'0011'

The two’s complement is returned when the input number is negative and width is specified:

>>> np.binary_repr(-3, width=5)'11101'
answeredMay 1, 2019 at 2:11
Tom Hale's user avatar

Comments

12

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

>>> "%08d" % int(bin(6)[2:])00000110
answeredMay 2, 2012 at 9:35
jedwards's user avatar

Comments

10

The best way is to specify the format.

format(a, 'b')

returns the binary value of a in string format.

To convert a binary string back to integer, use int() function.

int('110', 2)

returns integer value of binary string.

answeredApr 27, 2020 at 3:18
Pranjalya's user avatar

1 Comment

Better would be format(a, '08b') to obtain the format the user wanted.
6

.. 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'
answeredMay 2, 2012 at 9:47
thebjorn's user avatar

Comments

6

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)/2else:    binarynumber="0"return "".join(reversed(binarynumber))
answeredJun 8, 2018 at 16:40
Shadrack Kimutai's user avatar

4 Comments

number=number/2 gives float, sonumber=number//2 seams better, also I would replacenumber=number//2 withnumber//=2 andb=b+"0" withb+="0"
also, you don't have the 0 padding as the OP required
so ifnumber=7, your function returns "111" instead of "0111", this is unexpected.
true because at 7, you are still in the third bit. essentially the assumption is depending on the size to be received, the entire left side is made of zeroes
6

An even an easier way:

my_num = 6print(f'{my_num:b}')
Peter Mortensen's user avatar
Peter Mortensen
31.4k22 gold badges110 silver badges134 bronze badges
answeredSep 11, 2020 at 2:33
Raad Altaie's user avatar

Comments

4

You can use just:

"{0:b}".format(n)

In my opinion this is the easiest way!

answeredAug 11, 2020 at 17:21
Leha's user avatar

Comments

2

Assuming you want to parse the number of digits used to represent from a variable which is not always constant, a good way will be to use numpy.binary.

could be useful when you apply binary to power sets

import numpy as npnp.binary_repr(6, width=8)
answeredMar 11, 2020 at 13:31
ama's user avatar

Comments

1
('0' * 7 + bin(6)[2:])[-8:]

or

right_side = bin(6)[2:]'0' * ( 8 - len( right_side )) + right_side
eyllanesc's user avatar
eyllanesc
246k19 gold badges205 silver badges282 bronze badges
answeredSep 5, 2018 at 0:07
zerg's user avatar

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
0
def int_to_bin(num, fill):    bin_result = ''    def int_to_binary(number):        nonlocal bin_result        if number > 1:            int_to_binary(number // 2)        bin_result = bin_result + str(number % 2)    int_to_binary(num)    return bin_result.zfill(fill)
answeredMay 18, 2020 at 9:41
Dmity Bryuhanov's user avatar

Comments

0

Simple code with recursion:

 def bin(n,number=('')):   if n==0:     return(number)   else:     number=str(n%2)+number     n=n//2     return bin(n,number)
answeredDec 2, 2021 at 22:11
Mabel137's user avatar

1 Comment

Your answer could be improved with additional supporting information. Pleaseedit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answersin the help center.
0

The Python packageBinary Fractions has a full implementation of binaries as well as binary fractions. You can do your operation as follows:

from binary_fractions import Binaryb = Binary(6) # Creates a binary fraction stringb.lfill(8) # Fills to length 8

This package has many other methods for manipulating binary strings with full precision.

Peter Mortensen's user avatar
Peter Mortensen
31.4k22 gold badges110 silver badges134 bronze badges
answeredJul 16, 2021 at 14:49
Jonny Baron's user avatar

Comments

-1
    def convertToBinary(self, n):        result=""        if n==0:            return 0        while n>0:            r=n%2            result+=str(r)            n=int(n/2)        if n%2==0:            result+="0"        return result[::-1]
answeredOct 6, 2022 at 7:50
neda's user avatar

Comments

Protected question. To answer this question, you need to have at least 10 reputation on this site (not counting theassociation bonus). The reputation requirement helps protect this question from spam and non-answer activity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.