847

How do I convert an integer into a binary string in Python?

37 → '100101'
Mateen Ulhaq
27.9k21 gold badges122 silver badges155 bronze badges
asked Mar 31, 2009 at 3:04
1
  • For the opposite take, for a pure string processing algorithm, see this. Commented Mar 15, 2020 at 17:05

36 Answers 36

1
2
1

I feel Martijn Pieter's comment deserves to be highlighted as an answer:

binary_string = format(value, '0{}b'.format(width))

To me is is both clear and versatile.

answered May 1, 2019 at 6:32
Sign up to request clarification or add additional context in comments.

Comments

0

If you are willing to give up "pure" Python but gain a lot of firepower, there is Sage - example here:

sage: a = 15
sage: a.binary()
'1111'

You'll note that it returns as a string, so to use it as a number you'd want to do something like

sage: eval('0b'+b)
15
answered Dec 16, 2016 at 14:58

Comments

0

Here's a simple binary to decimal converter that continuously loops

t = 1
while t > 0:
 binaryNumber = input("Enter a binary No.")
 convertedNumber = int(binaryNumber, 2)
 print(convertedNumber)
print("")
answered Mar 10, 2017 at 16:14

1 Comment

This is the reverse order of what the OP wants. They are looking for int to binary. You provide binary to int.
0

This is my answer it works well..!

def binary(value) :
 binary_value = ''
 while value !=1 :
 binary_value += str(value%2)
 value = value//2
 return '1'+binary_value[::-1]
answered Apr 18, 2019 at 6:20

1 Comment

What if you pass the value 0? E.g. binary(0) will you get what you expect?
-1

Here is a (debugged) program that uses divmod to construct a binary list:

Program

while True:
 indecimal_str = input('Enter positive(decimal) integer: ')
 if indecimal_str == '':
 raise SystemExit
 indecimal_save = int(indecimal_str)
 if indecimal_save < 1:
 print('Rejecting input, try again')
 print()
 continue
 indecimal = int(indecimal_str)
 exbin = []
 print(indecimal, '<->', exbin)
 while True:
 if indecimal == 0:
 print('Conversion:', indecimal_save, '=', "".join(exbin))
 print()
 break
 indecimal, r = divmod(indecimal, 2)
 if r == 0:
 exbin.insert(0, '0')
 else:
 exbin.insert(0, '1')
 print(indecimal, '<->', exbin)

Output

Enter positive(decimal) integer: 8
8 <-> []
4 <-> ['0']
2 <-> ['0', '0']
1 <-> ['0', '0', '0']
0 <-> ['1', '0', '0', '0']
Conversion: 8 = 1000
Enter positive(decimal) integer: 63
63 <-> []
31 <-> ['1']
15 <-> ['1', '1']
7 <-> ['1', '1', '1']
3 <-> ['1', '1', '1', '1']
1 <-> ['1', '1', '1', '1', '1']
0 <-> ['1', '1', '1', '1', '1', '1']
Conversion: 63 = 111111
Enter positive(decimal) integer: 409
409 <-> []
204 <-> ['1']
102 <-> ['0', '1']
51 <-> ['0', '0', '1']
25 <-> ['1', '0', '0', '1']
12 <-> ['1', '1', '0', '0', '1']
6 <-> ['0', '1', '1', '0', '0', '1']
3 <-> ['0', '0', '1', '1', '0', '0', '1']
1 <-> ['1', '0', '0', '1', '1', '0', '0', '1']
0 <-> ['1', '1', '0', '0', '1', '1', '0', '0', '1']
Conversion: 409 = 110011001
answered Mar 15, 2020 at 18:10

Comments

-1

Along a similar line to Yusuf Yazici's answer

def intToBin(n):
 if(n < 0):
 print "Sorry, invalid input."
 elif(n == 0):
 print n
 else:
 result = ""
 while(n != 0):
 result += str(n%2)
 n /= 2
 print result[::-1]

I adjusted it so that the only variable being mutated is result (and n of course).

If you need to use this function elsewhere (i.e., have the result used by another module), consider the following adjustment:

def intToBin(n):
 if(n < 0):
 return -1
 elif(n == 0):
 return str(n)
 else:
 result = ""
 while(n != 0):
 result += str(n%2)
 n //= 2 #added integer division
 return result[::-1]

So -1 will be your sentinel value indicating the conversion failed. (This is assuming you are converting ONLY positive numbers, whether they be integers or longs).

answered Apr 26, 2014 at 5:41

1 Comment

Raising meaningful errors is preferable to printing output or returning sentinel values.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.