Python bin() Method

The bin() method converts an integer number to a binary string prefixed with 0b.

Syntax:

bin(num)

Parameters:

num: An integer.

Return type:

Returns a string.

The following examples converts integers into binary equivalents.

Example:
print("Binary equivalent of 5 is: ", bin(5))
print("Binary equivalent of 10 is: ", bin(10))
Output
Binary equivalent of 5 is:  0b101
Binary equivalent of 10 is:  0b1010

Use the __index__() method that returns an integer to get the binary of non-integer class, as shown below.

Example:
class Calc:
    lop=0
    rop=0
    def __index__(self):
        return self.lop + self.rop;
        
c = Calc()
c.lop=8
c.rop=7
print(bin(c))
Output
0b1111

If the arguement is of any other data type is passed, the TypeError exception is thrown.

Example:
print("Binary equivalent of A is: ", bin('A'))
Output
TypeError: 'str' object cannot be interpreted as an integer