python有一些内置函数,可以实现不同进制的转换。
oct函数(十进制转八进制)
根据官方文档的解释,oct()函数可以将十进制的整数转为八进制数。
>>> help(oct)
Help on built-in function oct in module builtins:
oct(number, /)
Return the octal representation of an integer.
>>> oct(342391)
'0o1234567'
hex函数(十进制转十六进制)
hex函数可用于将十进制的数字转化为十六进制的数,看到别人发的一篇博文,写的是能把其他进制的转为十六进制,应该是有问题的,给两个参数,指名base之后函数会报错。
>>> help(hex)
Help on built-in function hex in module builtins:
hex(number, /)
Return the hexadecimal representation of an integer.
>>> hex(12648430)
'0xc0ffee'
bin函数(十进制转二进制)
bin函数可用于将十进制的数转化为二进制的数。
>>> help(bin)
Help on built-in function bin in module builtins:
bin(number, /)
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
int函数(转十进制)
int函数的官方文档解释比较长,在这里就截取部分。如果输入的x是一个数字,那么就可以转化为整型,如果输入的x是字符串,给定base(默认为十进制,官方文档写的范围是2~36都可),可将字符串内的数根据base转换为相应的十进制数。
>>> help(int)
Help on class int in module builtins:
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
例子:
>>> int('0o1234567',base=8)
342391
>>> int("123ABC",base=16)
1194684