binary to int python code example

Example 1: convert int to binary python

# Python program to convert decimal to binary 
    
# Function to convert Decimal number  
# to Binary number  
def decimalToBinary(n):  
    return bin(n).replace("0b", "")  
    
# Driver code  
if __name__ == '__main__':  
    print(decimalToBinary(8))  
    print(decimalToBinary(18))  
    print(decimalToBinary(7))  
    
Output:
1000
1001

Example 2: binary to decimal in python

int(binaryString, 2)

Example 3: python binary string to int

>>> int('11111111', 2)
255

Example 4: py convert binary to int

# Convert integer to binary
>>> bin(3)
'0b11'

# Convert binary to integer
>>> int(0b11)
3

Example 5: how to convert from binary to base 10 in python

def getBaseTen(binaryVal):
	count = 0

	#reverse the string
    binaryVal = binaryVal[::-1]

    #go through the list and get the value of all 1's
	for i in range(0, len(binaryVal)):
    	if(binaryVal[i] == "1"):
            count += 2**i
    
    return count

Example 6: binary to decimal python

format(decimal ,"b")

Tags:

Java Example