The syntax of
bin() method is:
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
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.apple + self.orange + 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 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