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()