How do I convert an integer into a binary string in Python?
37 → '100101'
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.
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
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("")
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]
0? E.g. binary(0) will you get what you expect?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
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).