Python3内置函数——bin

先上英文文档:

 bin(x)

Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>>
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If prefix “0b” is desired or not, you can use either of the following ways.

>>>
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

See also format() for more information.

 

我们暂时只讨论x为整数型数据时发生的情形。

 

整理出函数信息表:

函数原型

bin(x)

参数解释

x

整数型,参数不可为空。

返回值

<class 'str'> 字符串类型,二进制整数。

函数说明

将一个整数转化为一个二进制整数,并以字符串的类型返回。

 

容易理解,该函数接受且只接受一个整数,并以二进制的形式返回。

>>> bin(0)
'0b0'
>>> print(bin(-729))
-0b1011011001

 

需要注意的是,该函数的返回值是一个字符串,不应将返回值进行计算。

>>> type(bin(729))
<class 'str'>
>>> bin(10) * 2
'0b10100b1010'

 

如果需要进行计算,需要使用int函数将字符串转换成int型数据。

>>> int(bin(729), base = 2)  #base参数不可空,否则会报错;base参数为空时默认为10进制。
729

 

当然了,参数不仅可以接受十进制整数,八进制、十六进制也是可以的,只要是int型数据就合法。

1 >>> bin(0b10010)
2 '0b10010'
3 >>> bin(0o12345)
4 '0b1010011100101'
5 >>> bin(0x2d9)
6 '0b1011011001'

 

posted @ 2017-08-17 23:40  田大可  阅读(2671)  评论(0编辑  收藏  举报