191

Is there any module or function in python I can use to convert a decimal number to its binary equivalent? I am able to convert binary to decimal using int('[binary_value]',2), so any way to do the reverse without writing the code to do it myself?

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
Paul
  • 1,959
  • 2
  • 12
  • 3
  • 1
    Unlike the linked question "convert to binary string", I think this question is different. I came here looking to convert an integer to a corresponding binary *array* (or boolean array), and I think that would be a sensible answer. – Sanjay Manohar Jan 16 '20 at 20:57
  • 1
    @SanjayManohar The pure string processing algorithm found [here](https://stackoverflow.com/a/60693697/8929814) could be adapted to do what you want. – CopyPasteIt Mar 15 '20 at 17:11

8 Answers8

286

all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)

>>> bin(10)
'0b1010'
>>> 0b1010
10
aaronasterling
  • 68,820
  • 20
  • 127
  • 125
83

Without the 0b in front:

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

Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:

f"{int_value:b}"
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
user136036
  • 11,228
  • 6
  • 46
  • 46
83
"{0:#b}".format(my_int)
Matt Williamson
  • 39,165
  • 10
  • 64
  • 72
52
def dec_to_bin(x):
    return int(bin(x)[2:])

It's that easy.

schmidmt
  • 676
  • 6
  • 4
  • 17
    **-1** - don't return an int. Also, `dec_to_bin(-1)` gives `ValueError: invalid literal for int() with base 10: 'b1'` – Eric Jan 08 '13 at 15:42
  • 2
    can you explain that [2:] ? – Patrick Ferreira Apr 18 '14 at 14:25
  • 2
    Try `bin(2)`. You don't get '10'. You get '0b10'. Same possible pit with `hex(2)` ('0x2'). So you want all but the first two characters. So you take a slice that starts after the first two characters. – leewz May 03 '14 at 05:04
  • 1
    @zero_cool if test_var = "Hello world" then test_var[2:] = "llo world" – Walter Apr 10 '18 at 07:30
  • @Eric could you explain why you shouldn't return an int?? – Wallace Jan 01 '20 at 12:42
  • 4
    @Wallace: because binary and decimal are a choice of how to _show_ the number, not part of the number itself. `dec_to_bin(0b101) == 101`, which is nonsense because none of operations you can apply to 101 have any relation to the original 5 - for instance, `dec_to_bin(0b101) + 1 == 102`. – Eric Jan 01 '20 at 18:29
  • TypeError: 'float' object cannot be interpreted as an integer – Chenying Gao May 12 '21 at 19:40
20

You can also use a function from the numpy module

from numpy import binary_repr

which can also handle leading zeros:

Definition:     binary_repr(num, width=None)
Docstring:
    Return the binary representation of the input number as a string.

    This is equivalent to using base_repr with base 2, but about 25x
    faster.

    For negative numbers, if width is not given, a - sign is added to the
    front. If width is given, the two's complement of the number is
    returned, with respect to that width.
flonk
  • 3,726
  • 3
  • 24
  • 37
13

I agree with @aaronasterling's answer. However, if you want a non-binary string that you can cast into an int, then you can use the canonical algorithm:

def decToBin(n):
    if n==0: return ''
    else:
        return decToBin(n/2) + str(n%2)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • `int(bin(10), 2)` yields `10`. `int(decToBin(10))` yields `101` and `int(decToBin(10), 2)` yields 5. Also, your function hit's recursion limits with `from __future__ import division` or python 3 – aaronasterling Aug 20 '10 at 04:47
  • 5
    @aaron, the latter point can be solved by switching to `//` (truncating division); the former, by switching the order of the two strings being summed in the `return`. Not that recursion makes any sense here anyway (`bin(n)[2:]` -- or a `while` loop if you're stuck on some old version of Python -- will be _much_ better!). – Alex Martelli Aug 20 '10 at 04:56
  • 1
    This is awesome! it could go with the **lambda** way too :] `binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)` – Aziz Alto Jun 15 '15 at 01:52
  • @AzizAlto I get a busload full of numbers with lots of `e-`, also in the recursive call dectobin. – Timo Feb 07 '18 at 16:18
  • 2
    @Timo lol apparently you are using Python3 just change `binary(n/2)` to `binary(n//2)` then you won't get that busload :-) – Aziz Alto Feb 07 '18 at 16:42
  • I think it is better to use `if n==0: return '0'` instead of `if n==0: return ''` since for n=0 your code return empty string which is incorrect answer. Although this approach gives you an extra 0 on left for non-zero inputs. – user3342981 Dec 28 '22 at 18:54
7
n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
    a=int(float(n%2))
    k.append(a)
    n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
    string=string+str(j)
print('The binary no. for %d is %s'%(x, string))
harry
  • 71
  • 1
  • 3
2

For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:

  1. Get the integer and fractional part.

    from decimal import *
    a = Decimal(3.625)
    a_split = (int(a//1),a%1)
    
  2. Convert the fractional part in its binary representation. To achieve this multiply successively by 2.

    fr = a_split[1]
    str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
    

You can read the explanation here.

Kalouste
  • 81
  • 1
  • 2