I'm trying to create an algorithm that converts decimals to binary. I can't use the built-in function in python to do so. This is what I've got.
n=int(input("enter a number"))
while n > 1:
print(n%2)
n //= 2
if n % 2 ==0:
print(n%2)
else:
print(n%2)
I'm completely fine with the 1's and 0's being printed in a separate line, as long as they're correct.
-
I tough this link give what you looking for :codereview.stackexchange.com/questions/134154/…Pasha– Pasha2019年10月13日 06:11:01 +00:00Commented Oct 13, 2019 at 6:11
-
what if your number is negative?Azat Ibrakov– Azat Ibrakov2019年10月13日 06:18:41 +00:00Commented Oct 13, 2019 at 6:18
8 Answers 8
It should be:
n=int(input("enter a number\n"))
while n >= 1: # Should be >= 1, not > 1.
print(n%2)
n //= 2
# Removed if else.
Also, note that this will print binary in the reverse order.
For the input 6, the output will be:
0
1
1
Not:
1
1
0
If you want the later one, then you can store it in a list first and then print the list in the reverse order.
Comments
This works quite well, returns a string, and it's a separate function, so you don't pollute your code:
def int2bin( num ) :
result = []
while num :
result.append( str(num & 1) )
num >>= 1
return ''.join( result[::-1] )
The result:
>>> int2bin(4)
'100'
3 Comments
while num : with while num or len(result) == 0 : to fix the case with 0num >= 1, but you are correct, I should have make it work for 0 as wellYou can do the division and modulo in one step:
while n:
n, d = divmod(n, 2)
print(d)
This is basically the core of all answers. But it prints nothing for n = 0. And strange things happen for negative n. Let's handle all integers:
A complete program (without reversing the digits) may look like this:
if n == 0:
print(0)
elif n < 0:
print('-')
n = -n
while n:
n, d = divmod(n, 2)
print(d)
Comments
If you want a track of what is going on, add some prints, and your binary result, where are you saving it? I propose a str, could be a list of int, I don't know, but this is one way (using your logic as a base):
n=int(input("enter a number"))
binary = ""
while n > 1:
rest = n % 2
n //= 2
print("rest: {}".format(rest), "step: {}".format(n))
binary = str(rest) + binary
if(n>=1):
binary ="1" + binary
print(binary)
example:
enter a number: <b>2045</b>
1. rest: 1 step: 1022
2. rest: 0 step: 511
3. rest: 1 step: 255
4. rest: 1 step: 127
5. rest: 1 step: 63
6. rest: 1 step: 31
7. rest: 1 step: 15
8. rest: 1 step: 7
9. rest: 1 step: 3
10. rest: 1 step: 1
11111111101
Comments
you can simply do like this:
n=int(input("Enter a number\n"))
res=""
while n >= 1:
res=res+str(n%2)
n //= 2
print(int(res[::-1]))
sample output 1:
Enter a number
10
1010
sample output 2:
Enter a number
99
1100011
Comments
Use bin, if you want a simple method and clean code, here is my code
n = int(input('Input any Integer: '))
dim = str(bin(n)).split('0b', 1)[1].strip()
print('\n'.join([n for n in dim]))
And then use '\n'.join(...) to print all number per each line
Comments
You can use method bin()
def decimalToBinary(n):
return bin(n).replace("0b","")
Comments
Just another compact solution with recursion:
Note: The output will be an one line string
def dec_to_bin(n):
if not n: # When n==0.
return ''
return dec_to_bin(n//2) + str(n%2)
Example:
print(dec_to_bin(19))
Output:
10011