當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。