In this tutorial, we will learn about the python bin() method and its uses.
What is Python bin() Method?
The bin() is a built-in method in python that will take an integer and return the given integer’s binary representation into a string format.
The syntax of the bin() method is:
Python bin() Parameters
The bin() method will take only a single parameter as an integer.
Let’s see an example of the bin() python method.
Example 1: Convert integer to binary using bin() method.
We can see that the bin() method is returning the binary equivalent of the given number, and the 0b is the prefix representation of the binary string, which will remain the same with all the integer numbers.
If the given value is not an integer, the bin() method has to implement __index__() method to return an integer.
Example 2: Convert an object to binary using __index__() method with bin() method.
When we execute the above program, we will get the following results.
Here, we are giving an object of class Sum as a parameter to the bin() method.
When we give the non-integer value of the bin() method, it will throw an error because the bin() method only takes an integer value as a parameter.
But in the above program, the bin() method will not raise an error even when we are giving an object of the Sum class that is not an integer.
This is because we have implemented the __index__() method, which returns an integer. This integer is then supplied to the bin() method.