將十進制 (decimal) 轉換為二進制 (binary),八進制 (octal) 和十六進制 (hexadecimal)


在編程和日常電腦應用中,有時我們需要將十進制數轉換為二進制,八進制或十六進制。 在此示例中,我們將為此編寫三個數字系統間數值轉換的函數:  dec_to_bin() - 將十進制數轉換為二進制, dec_to_oct() - 將十進制數轉換為八進制, dec_to_hex() - 將十進制數轉換為十六進制。

# Functions dec_to_bin, dec_to_oct, and dec_to_hex

def dec_to_bin(i):
   if (i == 0):
   b = "0"
   else:
   b = ""
   while (i != 0):
         r = i % 2
         b = str(r)+b
         i = i // 2
   return b

def dec_to_oct(i):
   if (i == 0):
      o = "0"
   else:
      o = ""
      while (i != 0):
         r = i % 8
         o = str(r)+o
         i = i // 8
   return o

def dec_to_hex(i):
   xdigit = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
      "A", "B", "C", "D", "E", "F"]
   if (i == 0):
      x = "0"
   else:
      x = ""
      while (i != 0):
         r = i % 16
         x = xdigit[r]+x
         i = i // 16
   return x

i = int(input("Enter an unsigned integer: "))

print("Binary representation of decimal integer %d is %s."
   % (i,dec_to_bin(i)))
print("Octal representation of decimal integer %d is %s."
   % (i,dec_to_oct(i)))
print("Hexadecimal representation of decimal integer %d is %s."
   % (i,dec_to_hex(i)))

在此示例中,我們輸入十進制數 123,結果如下
Enter an unsigned integer: 123
Binary representation of decimal integer 123 is 1111011.
Octal representation of decimal integer 123 is 173.
Hexadecimal representation of decimal integer 123 is 7B.