码迷,mamicode.com
首页 > 编程语言 > 详细

Python3内置函数——bin

时间:2017-08-18 00:02:19      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:十六进制   ber   title   英文   func   fine   desc   转换   form   

先上英文文档:

 

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参数不可空,否则会报错
729

 

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

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

 

Python3内置函数——bin

标签:十六进制   ber   title   英文   func   fine   desc   转换   form   

原文地址:http://www.cnblogs.com/Dake-T/p/7385096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!