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'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM