python中bin函數的用法:bin函數主要是用來返回一個整形int或者一個長整形long int的二進制表示,相當于是用來獲取數字的二進制值;bin函數的語法格式:“bin(x)”,這里x指的是int或者long int數字,并且必須為整數。
具體實例分析:
實例1
print(bin(3))print(type(bin(3)))
print(bin(-10))
print(type(bin(-10)))
運行以上代碼返回的結果為:
0b11<class 'str'>
-0b1010
<class 'str'>
實例2
將數字轉換為二進制字符串的python代碼
# python code to convert number to binary# an example of bin() function in Python
num1 = 55 # number (+ve)
num2 = -55 # number (-ve)
# converting to binary
bin_str = bin(num1)
print("Binary value of ", num1, " is = ", bin_str)
bin_str = bin(num2)
print("Binary value of ", num2, " is = ", bin_str)
輸出結果為:
Binary value of 55 is = 0b110111Binary value of -55 is = -0b11011