Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm pretty new to programation so I came here for you "pros" to help me fidding out, how to make a program that convert integer(from the user input) to a binary code, without using the bin() function.

Here is what I started to do by myself:
Python
nDecimal = eval(input("entrer un décimal positif :"))
print("Le nombre décimal entrer est:", nDecimal)

#transformation into binairy:


while nDecimal != 1 or 0:
    for i in nDecimal:
        i = nDecimal % len(nDecimal)
        if i > 1 or 0:
            i += 1
        else:
            print("votre nombre", nDecimal, "en binaire est:", i)
            break


Of course that code doesn't work :(. I tried to use the modulo of the user input and add to it 1 until the "nDecimal" is not divisible anymore.

Ps: Sorry for my sh*tty english.
Posted
Updated 26-Jan-15 22:12pm
v3

1 solution

To convert a decimal number to its binary equivalent you need to take the remainder of successively dividing by 2, and print in reverse. For example the number 13 is
13 / 2 = 6 rem 1
 6 / 2 = 3 rem 0
 3 / 2 = 1 rem 1
 1 / 2 = 0 rem 1
      binary = 1101

Try
Python
nDecimal = eval(input("entrer un décimal positif :"))
print("Le nombre décimal entrer est:", nDecimal)
nbin=[]
while nDecimal > 0:
    value = int(nDecimal % 2)
    # print (value)
    nDecimal = int(nDecimal / 2)
    nbin.append(value)
nbin.reverse()
print("Le nombre binaire est", end=": ")
for x in nbin:
    print(x, end='')
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900