python进制转换


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值