Python中可以使用內置函數bin()
, oct()
, hex()
來進行任意進制之間的轉換。具體方法如下:
bin(number)
,將十進制數轉換為二進制數。decimal_num = 10
binary_num = bin(decimal_num)
print(binary_num) # 輸出:0b1010
oct(number)
,將十進制數轉換為八進制數。decimal_num = 10
octal_num = oct(decimal_num)
print(octal_num) # 輸出:0o12
hex(number)
,將十進制數轉換為十六進制數。decimal_num = 10
hexadecimal_num = hex(decimal_num)
print(hexadecimal_num) # 輸出:0xa
int()
函數,并指定原始數字的進制基數。binary_num = '1010'
decimal_num = int(binary_num, 2)
print(decimal_num) # 輸出:10
octal_num = '12'
decimal_num = int(octal_num, 8)
print(decimal_num) # 輸出:10
hexadecimal_num = 'a'
decimal_num = int(hexadecimal_num, 16)
print(decimal_num) # 輸出:10