def binary_to_octal(binary_str):
decimal = int(binary_str, 2)
return oct(decimal)[2:] # 去掉 '0o' 前缀
def binary_to_decimal(binary_str):
return int(binary_str, 2)
def binary_to_hexadecimal(binary_str):
decimal = int(binary_str, 2)
return hex(decimal)[2:].upper() # 去掉 '0x' 前缀并转换为大写
def octal_to_binary(octal_str):
decimal = int(octal_str, 8)
return bin(decimal)[2:] # 去掉 '0b' 前缀
def octal_to_decimal(octal_str):
return int(octal_str, 8)
def octal_to_hexadecimal(octal_str):
decimal = int(octal_str, 8)
return hex(decimal)[2:].upper() # 去掉 '0x' 前缀并转换为大写
def decimal_to_binary(decimal_str):
return bin(int(decimal_str))[2:] # 去掉 '0b' 前缀
def decimal_to_octal(decimal_str):
return oct(int(decimal_str))[2:] # 去掉 '0o' 前缀
def decimal_to_hexadecimal(decimal_str):
return hex(int(decimal_str))[2:].upper() # 去掉 '0x' 前缀并转换为大写
def hexadecimal_to_binary(hex_str):
decimal = int(hex_str, 16)
return bin(decimal)[2:] # 去掉 '0b' 前缀
def hexadecimal_to_octal(hex_str):
decimal = int(hex_str, 16)
return oct(decimal)[2:] # 去掉 '0o' 前缀
def hexadecimal_to_decimal(hex_str):
return int(hex_str, 16)
def main():
type_input = input("请输入类型 (bin, oct, dec, hex): ").strip().lower()
value_input = input("请输入数值: ")
if type_input == 'bin':
print(f"二进制: {value_input}")
print(f"八进制: {binary_to_octal(value_input)}")
print(f"十进制: {binary_to_decimal(value_input)}")
print(f"十六进制: {binary_to_hexadecimal(value_input)}")
elif type_input == 'oct':
print(f"八进制: {value_input}")
print(f"二进制: {octal_to_binary(value_input)}")
print(f"十进制: {octal_to_decimal(value_input)}")
print(f"十六进制: {octal_to_hexadecimal(value_input)}")
elif type_input == 'dec':
print(f"十进制: {value_input}")
print(f"二进制: {decimal_to_binary(value_input)}")
print(f"八进制: {decimal_to_octal(value_input)}")
print(f"十六进制: {decimal_to_hexadecimal(value_input)}")
elif type_input == 'hex':
print(f"十六进制: {value_input}")
print(f"二进制: {hexadecimal_to_binary(value_input)}")
print(f"八进制: {hexadecimal_to_octal(value_input)}")
print(f"十进制: {hexadecimal_to_decimal(value_input)}")
else:
print("输入类型无效,请输入 bin, oct, dec 或 hex。")
if __name__ == "__main__":
main()
标签:binary,转换,进制,python,decimal,print,str,octal,input
From: https://www.cnblogs.com/jarico/p/18439604