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