Python bin()

The bin() method converts and returns the binary equivalent string of a given integer. If the parameter isn't an integer, it has to implement __index__() method to return an integer.

The syntax of bin() method is:

bin(num)

bin() Parameters

The bin() method takes a single parameter:

  • num - an integer number whose binary equivalent is to be calculated.
    If not an integer, should implement __index__() method to return an integer.

Return value from bin()

The bin() method returns the binary string equivalent to the given integer.

If not specified an integer, it raises a TypeError exception highlighting the type cannot be interpreted as an integer.


Example 1: Convert integer to binary using bin()

number = 5
print('The binary equivalent of 5 is:', bin(number))

When you run the program, the output will be:

The binary equivalent of 5 is: 0b101

The prefix 0b represents that the result is a binary string.


Example 2: Convert an object to binary implementing __index__() method

class Quantity:
    apple = 1
    orange = 2
    grapes = 2
    
    def __index__(self):
        return self.apple + self.orange + self.grapes
        
print('The binary equivalent of quantity is:', bin(Quantity()))

When you run the program, the output will be:

The binary equivalent of quantity is: 0b101

Here, we've sent an object of class Quantity to the bin() method.

The bin() method doesn't raise an error even if the object Quantity is not an integer.

This is because, we have implemented the __index__() method which returns an integer (sum of fruit quantities). This integer is then supplied to the bin() method.