Python bin() Function

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

Python bin() function

For example, the binary equivalent of 2 is 0b10.

The result is a valid Python expression. If the parameter of bin()  is not a Python int object, it has to define an __index__() method that returns an integer.

Python bin() Syntax

The syntax of bin() function is:

bin( num )

The function bin() takes a number as a parameter which is converted to a binary number. If the number num is not an integer, then __index__() method is implemented to return an integer.

Python bin() Example: Convert integer to binary using bin()

>>> bin(2)
>>> bin(-5)

As you can see in the example above, the Python bin() function returns the equivalent binary number prefixed with 0b of an integer.

In case you don’t want those prefixed ob you can use format() function.

For example:

>>> format(2, 'b')

As we stated earlier, Python implements a __index__() function that returns an integer if the parameter supplied to bin() function is not an integer.

Noe, let’s see how it is implemented in the program.

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

Class Sum:
  a = 2
  b = 4
  def __index__(self):
    return self.a + self.b

#Creating a Python object of class Sum
x = Sum()
print('Equivalent binary number is:', bin(x))

This will generate following output.

Equivalent binary number is: 0b110

That is how __index__() function is used to return an integer when we don’t have an integer as argument in Python bin() function.