1

I'm having an issue with this piece of code I wrote. I'm trying to convert an integer input and print an output with its equivalent in binary base. For example for 5 it should drop an output of '101' however it just prints '10' like if it doesn't take into account the last digit. Please any comments would be greatly appreciated

T = raw_input()
for i in range(0, int(T)):
    n = raw_input()
    dec_num = int(n)
    cnv_bin = ''
    while dec_num//2 > 0:        
        if dec_num%2 == 0:
            cnv_bin += '0'
        else:
            cnv_bin += '1'
        dec_num = dec_num//2
    print cnv_bin[::-1]
1

3 Answers 3

1
while dec_num//2 > 0:

should be:

while dec_num > 0:

The first time through the loop, 5//2==2, so it continues.
The second time through the loop, 2//2==1, so it continues.
The third time, 1//2==0 and the loop quits without handling the last bit.

Also, you can just do the following to display a number in binary:

print format(dec_num,'b')

Format string version:

print '{0} decimal is {0:b} binary.'.format(5)
Sign up to request clarification or add additional context in comments.

Comments

1

Why not use the build-in function bin()? eg:

bin(5)

output

0b101

If you don't want the prefix(0b), you can exclude it.

bin(5)[2:]

hope to be helpful!

1 Comment

thanks a lot! actually the assignment was to use find the binary equivalent without using the formula...but will keep in mind for future occasions
0
import math
def roundup(n):
    return math.ceil(n)
D = eval(input("Enter The Decimal Value: "))
n = roundup(math.log2(D+1))-1
bi = 0
di = D
qi = 0
i = n
print("Binary Value:",end = " ")
while(i>=0):
    qi = math.trunc(di/2**i)
    bi = qi
    print(bi,end = "")
    di = di - bi*(2**i)
    i = i-1

1 Comment

This is a python 3 solution, Enter a Decimal to print a Binary value

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.