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

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.

Example 1: Convert integer to binary using bin()

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


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.grapes
print('The binary equivalent of quantity is:', bin(Quantity()))


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.

Did you find this article helpful?