0

I'm trying to use a function (dec2bin()) to convert decimal numbers to binary. I see the input number being printed as binary but in the wrong order. What do I need to change? Or do I need to start over?

Here is the code with the function at first then the program:

def dec2bin(value):
  if value > 1:
    dec2bin(value//2)
    print (value%2, end = '')

invalue_ok = False
invalue = 0
while invalue_ok is False:
   invalue = int(input("Give a value: "))
   if invalue > 65535:
       print ("Wrong. Number too big. Try again.")
   elif invalue < 0:
       print ("Wrong. Can only handle positive numbers.")
   if invalue < 256:
       print ("Number", invalue, "fits in one byte and in binary is ", dec2bin(invalue))
   else:
        print ("Number", invalue, "fits in 16 bytes and in binary is", dec2bin(invalue))`

The output looks like this: Give a value: 234 1101010Number 234 fits in one byte and in binary is None

What can I do to get it right?

Zephyr
  • 11,891
  • 53
  • 45
  • 80

2 Answers2

0

it works with

if value>0:

it's in the good order

AymericNgy
  • 43
  • 1
  • 7
0

There are three easier ways to do it:

The format method:

binary = "{0:b}".format(*number*)

The bin method (this also works with negative numbers):

binary = bin(*number*)

Or a function from this thread:

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
        return result[::-1]

binary = intToBin(*number*)