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)

1. bin() Parameters

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.

2. Return value from bin()

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.

3. Example 1: Convert integer to binary using bin()

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

Output

The binary equivalent of 5 is: 0b101

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

4. 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()))

Output

The binary equivalent of quantity is: 0b101

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

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.