在Python中如何快速将Decimal转换为其他基数?

2021年4月3日19:37:46 发表评论 778 次浏览

给定十进制数字, 将其转换为二进制, 八进制和十六进制数字。这是将十进制转换为二进制, 十进制转换为八进制以及十进制转换为十六进制的函数。

例子:

Input : 55
Output : 55  in Binary :  0b110111
         55 in Octal :  0o67
         55  in Hexadecimal :  0x37

Input : 282
Output : 282  in Binary :  0b100011010
         282 in Octal :  0o432
         282  in Hexadecimal :  0x11a

一种解决方案是使用以下文章中讨论的方法。

任何基数转换为十进制, 反之亦然

Python为标准基础转换(例如bin(), hex()和oct())提供直接函数

# Python program to convert decimal to binary, # octal and hexadecimal
  
# Function to convert decimal to binary
def decimal_to_binary(dec):
     decimal = int (dec)
  
     # Prints equivalent decimal
     print (decimal, " in Binary : " , bin (decimal))
  
# Function to convert decimal to octal
def decimal_to_octal(dec):
     decimal = int (dec)
  
     # Prints equivalent decimal
     print (decimal, "in Octal : " , oct (decimal))
  
# Function to convert decimal to hexadecimal
def decimal_to_hexadecimal(dec):
     decimal = int (dec)
  
     # Prints equivalent decimal
     print (decimal, " in Hexadecimal : " , hex (decimal))
  
# Driver program
dec = 32
decimal_to_binary(dec)
decimal_to_octal(dec)
decimal_to_hexadecimal(dec)

输出如下:

32  in Binary :  0b100000
32 in Octal :  0o40
32  in Hexadecimal :  0x20

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: