1

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.

2

8 Answers 8

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

this answer helped me very much, BUT it doesn't work for 0. I had to add that edge condition to this method so it would return '0'.
@Alexandre you may replace while num : with while num or len(result) == 0 : to fix the case with 0
@Alexandre the OP specifically asked for the algorithm that works with num >= 1, but you are correct, I should have make it work for 0 as well
1

You 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

0

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

0

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

0

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

0

You can use method bin()

def decimalToBinary(n): 
    return bin(n).replace("0b","") 

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.