The bin() Function is a standard library function in Python. It converts an integer number to an equivalent binary number.
Python bin() Function Syntax
bin(x)
Parameter: It takes a single parameter x, which is an integer number whose binary equivalent we want to find out. If x is not a Python int object, it has to define an __index__() method that returns an integer.
Return value: This function returns a binary String equivalent to the given integer number.
Python bin() Function Example
In the following example, we are using bin() function to find out the binary equivalent of an integer number 10.
#integer number num = 10 print('The binary equivalent of 10 is:', bin(num))
Output:
The bin() function example implementing __index__() method
When the object that we pass to the bin() function is not an integer then it has to define an _index_() method. Lets take an example to understand this:
Here we are passing an object of class Pets
to the bin() function and it doesn’t return any error even though the object is not an integer, this is because we have implemented the _index_() method, which returns the sum of total animal counts which is an integer.
class Pets: dogs = 2 cats = 3 horses = 3 def __index__(self): return self.dogs + self.cats + self.horses print('The binary equivalent of Pets is:', bin(Pets()))
Output:
Reference:
Built-in function bin()
Related Posts:
Leave a Reply