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