Python中的bin()

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

null

语法: 宾(a)

参数:a: 要转换的整数

返回值: 整数或整数对象的二进制字符串。

例外情况: 在参数中发送浮点值时引发TypeError。

Python bin()示例

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

Python3

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


输出:

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

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享