1

I am currently writing a Python 3 program to convert decimal to binary among other things for a Uni assignment.

I've nailed everything except for this in the first stage (decimal to binary).

dec = int(input("Enter a number: "))

while dec > 0 or dec == 0:
    if dec > 0:
        rem = dec % 2
        dec = dec // 2
        print(rem, end = "")

The output gives the binary number correctly, however it is in reverse. Can you please tell me how to reverse the output or reverse the conversion process or something to correct the output?

EDIT: I cannot use in-built functions such as bin(dec), etc. Thanks!

2 Answers2

0

The above code is not decimal to binary, instead it is an example of dividend/reminder. You can do that as follows:

  dec, rem = divmod(dec, 2)

If you still want to convert decimal to binary do -

 bin(dec)

Based on the comment, would this help?

def dec2bin(d):
  s = ''
  while d>0:
    d,r = divmod(d, 2)
    s += str(r)

  return s[::-1]

>>> dec2bin(6)
'110'
RG_Glpj
  • 27
  • 4
  • Binary is literally remainders. Also, I cannot use in built functions such as bin etc. sorry for not specifying, I will edit main post – Ryan Vukasinovic Apr 21 '16 at 16:33
0

python program to convert the given binary to decimal, octal and hexadecimal number and vice versa. conversions of all bases with each other.

 x = int(input("press 1 for dec to oct,bin,hex \n press 2 for bin to dec,hex,oct \n press 3 for oct to bin,hex,dec \n press 4 for hex to bin,dec,oct \n"))


   if x is 1:

  decimal =int(input('Enter the decimal number: '))

  print(bin(decimal),"in binary.")
 print(oct(decimal),"in octal.")
    print(hex(decimal),"in hexadecimal.")

      if x is 2:

       binary = input("Enter number in Binary Format: ");

  decimal = int(binary, 2);
  print(binary,"in Decimal =",decimal);
  print(binary,"in Hexadecimal =",hex(decimal));
  print(binary,"in octal =",oct(decimal));

    if x is 3:

      octal = input("Enter number in Octal Format: ");

      decimal = int(octal, 8);
      print(octal,"in Decimal =",decimal);
      print(octal,"in Hexadecimal =",hex(decimal));
      print(octal,"in Binary =",bin(decimal));

          if x is 4:

         hex = input("Enter number in hexa-decimal Format: ");

      decimal = int(hex, 16);
        print(hex,"in Decimal =",decimal);
      print(hex,"in octal =",oct(decimal));
        print(hex,"in Binary =",bin(decimal));
YogVj
  • 1