二进制转换Python输出问题

时间:2016-04-21 16:13:05

标签: python-3.x

我目前正在编写一个Python 3程序,将十进制转换为二进制,以便进行Uni赋值。

我已经在第一阶段(十进制到二进制)中除了这个以外的所有内容。

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

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

输出正确地给出二进制数,但它是相反的。 您能否告诉我如何反转输出或反转转换过程或更正输出?

编辑:我不能使用内置函数,如bin(dec)等。 谢谢!

2 个答案:

答案 0 :(得分:0)

上面的代码不是十进制到二进制,而是一个红利/提醒的例子。你可以这样做:

  dec, rem = divmod(dec, 2)

如果您仍想将十进制转换为二进制,请执行 -

 bin(dec)

根据评论,这会有帮助吗?

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

  return s[::-1]

>>> dec2bin(6)
'110'

答案 1 :(得分:0)

python程序,用于将给定的二进制转换为十进制,八进制和十六进制数,反之亦然。 所有碱基彼此之间的转换。

 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));