有时候,我们需要知道十进制,二进制,十六进制之间的数字。可是用手算又累又麻烦,所以我用Python写了一个进制转换的代码。废话不多说,直接上代码。
def decimal_to_binary(decimal):
return bin(decimal)[2:]
def decimal_to_hexadecimal(decimal):
return hex(decimal)[2:]
def binary_to_decimal(binary):
return int(binary, 2)
def binary_to_hexadecimal(binary):
decimal = binary_to_decimal(binary)
return decimal_to_hexadecimal(decimal)
def hexadecimal_to_decimal(hexadecimal):
return int(hexadecimal, 16)
def hexadecimal_to_binary(hexadecimal):
decimal = hexadecimal_to_decimal(hexadecimal)
return decimal_to_binary(decimal)
def main():
print("请选择转换类型:")
print("1. 十进制转二进制")
print("2. 十进制转十六进制")
print("3. 二进制转十进制")
print("4. 二进制转十六进制")
print("5. 十六进制转十进制")
print("6. 十六进制转二进制")
choice = int(input("请输入选项:"))
if choice == 1:
decimal = int(input("请输入十进制数:"))
binary = decimal_to_binary(decimal)
print("二进制数为:", binary)
elif choice == 2:
decimal = int(input("请输入十进制数:"))
hexadecimal = decimal_to_hexadecimal(decimal)
print("十六进制数为:", hexadecimal)
elif choice == 3:
binary = input("请输入二进制数:")
decimal = binary_to_decimal(binary)
print("十进制数为:", decimal)
elif choice == 4:
binary = input("请输入二进制数:")
hexadecimal = binary_to_hexadecimal(binary)
print("十六进制数为:", hexadecimal)
elif choice == 5:
hexadecimal = input("请输入十六进制数:")
decimal = hexadecimal_to_decimal(hexadecimal)
print("十进制数为:", decimal)
elif choice == 6:
hexadecimal = input("请输入十六进制数:")
binary = hexadecimal_to_binary(hexadecimal)
print("二进制数为:", binary)
else:
print("无效的选项")
if __name__ == "__main__":
main()