📜  Python中的 bin()

📅  最后修改于: 2022-05-13 01:55:18.047000             🧑  作者: Mango

Python中的 bin()

Python bin()函数返回给定整数的二进制字符串。

Python bin() 示例

示例 1:使用 bin() 方法将整数转换为二进制

Python3
# Python code to demonstrate working of
# bin()
 
# declare variable
num = 100
 
# print binary number
print(bin(num))


Python3
# Python code to demonstrate working of
# bin()
 
# function returning binary string
def Binary(n):
    s = bin(n)
 
    # removing "0b" prefix
    s1 = s[2:]
    return s1
 
print("The binary representation of 100 (using bin()) is : ", end="")
print(Binary(100))


Python3
# Python code to demonstrate working of
# bin()
class number:
    num = 100
 
    def __index__(self):
        return(self.num)
 
print(bin(number()))


输出:

0b1100100

示例 2:使用用户定义函数将整数转换为二进制

Python3

# Python code to demonstrate working of
# bin()
 
# function returning binary string
def Binary(n):
    s = bin(n)
 
    # removing "0b" prefix
    s1 = s[2:]
    return s1
 
print("The binary representation of 100 (using bin()) is : ", end="")
print(Binary(100))

输出:

The binary representation of 100 (using bin()) is : 1100100

示例 3:使用 bin() 和 __index()__ 将用户定义的对象转换为二进制

这里我们将类的对象发送到 bin 方法,我们使用的是Python特殊方法 __index()__ 方法,该方法总是返回正整数,如果值不是整数,则不会出现上升错误。

Python3

# Python code to demonstrate working of
# bin()
class number:
    num = 100
 
    def __index__(self):
        return(self.num)
 
print(bin(number()))

输出:

0b1100100