Python bin() 函式



Python bin() 函式是一個內建函式,用於將給定的整數轉換為其二進位制等效值,該值表示為字串。此操作的最終結果始終以字首0b開頭,表示結果為二進位制。

如果 bin() 函式的指定引數不是整數物件,我們需要實現__index__()方法,該方法將數字物件轉換為整數物件。

語法

以下是 Python bin() 函式的語法:

bin(i) 

引數

Python bin() 函式接受單個引數:

  • i - 此引數表示整數物件。

返回值

Python bin() 函式返回指定整數的二進位制表示。

示例

以下是一些演示 bin() 函式工作原理的示例:

示例 1

以下示例顯示了 Python bin() 函式的基本用法。在這裡,我們建立一個整數物件,然後應用 bin() 函式將其轉換為二進位制形式。

i = 12 
binaryRepr = bin(i)
print("The binary representation of given integer:", binaryRepr)

執行上述程式時,將產生以下結果:

The binary representation of given integer: 0b1100

示例 2

在下面的程式碼中,我們演示瞭如何從 bin 操作的結果中省略初始字首 (0b)。

i = 12 
binaryRepr = bin(i)
# Omiting the prefix 0b
output = binaryRepr[2:]
print("The binary representation of given integer:", output)

以下是上述程式碼的輸出:

The binary representation of given integer: 1100

示例 3

下面的程式碼演示了 bin() 函式與負整數物件一起工作的情況。

i = -14 
binaryRepr = bin(i)
print("The binary representation of given integer:", binaryRepr)

上述程式碼的輸出如下:

The binary representation of given integer: -0b1110

示例 4

在下面的程式碼中,我們將演示如何一起使用 __index__() 和 bin() 方法將員工的 ID 轉換為其二進位制表示。

class Id:
   emp_id = 121
   def __index__(self):
      return self.emp_id

binaryRepr = bin(Id())
print("The binary representation of given employee ID:", binaryRepr)

以下是上述程式碼的輸出:

The binary representation of given employee ID: 0b1111001
python_built_in_functions.htm
廣告