在Python中快速将十进制转换为其他基数

给定一个十进制数,将其转换为二进制、八进制和十六进制数。这是一个将十进制转换为二进制、十进制转换为八进制和十进制转换为十六进制的函数。

null

例如:

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

本文由 普拉莫德·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

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

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享