当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python bin()用法及代码示例


将小数转换为二进制始终是python dev项目和竞争性编程中所必需的重要实用程序。具有速记函数来实现此目的在需要快速转换而无需编写长代码的情况下总是很方便的,这由“ bin()”提供。本文对此进行了讨论。

将十进制转换为二进制的自编程方法

1.使用递归

# Function to print binary number for the  
# input decimal using recursion 
def decimalToBinary(n):
  
    if n > 1:
        # divide with integral result  
        # (discard remainder)  
        decimalToBinary(n//2)  
  
  
    print (n%2,end="")          
  
# Driver code 
if __name__ == '__main__':
    decimalToBinary(8) 
    print("\r") 
    decimalToBinary(18) 
    print("\r") 
    decimalToBinary(7) 
    print

输出:


1000
10010
111

2.使用循环

# Python code to demonstrate naive method 
# using loop  
  
# function returning binary string 
def Binary(n):
    binary = "" 
    i = 0
    while n > 0 and i<=8:
        s1 = str(int(n%2)) 
        binary = binary + s1 
        n /= 2
        i = i+1
        d = binary[::-1] 
    return d 
  
print("The binary representation of 100 (using loops) is:",end="") 
print(Binary(100))

输出:

The binary representation of 100 (using loops) is:001100100

使用bin()

使用bin()可以减少编码所需的时间,并且还可以消除上述两种方法中可能遇到的麻烦。

用法:
bin(a)
参数:
a: an integer to convert
返回值:
A binary string of an integer or int object.
Exceptions:
Raises TypeError when a float value is sent in arguments.
# 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



相关用法


注:本文由纯净天空筛选整理自 bin() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。