The bin()
is a built-in function in Python that takes an integer and returns the binary equivalent of the integer in string format. If the given input is not an integer, then the __index__()
method needs to be implemented to return an integer. Otherwise, Python will throw a TypeError exception.
bin() Syntax
The syntax of the bin()
method is
bin(num)
bin() Parameters
The bin()
function takes a single argument, an integer whose binary representation will be returned.
If the given input is not an integer, then the __index__()
method needs to be implemented to return a valid integer.
bin() Return Value
The bin()
method returns the binary equivalent string of the given integer.
Exceptions: Raises TypeError when a float value is given as an input to the bin()
function.
Example 1: Convert integer to binary using bin() method
# Python code to demonstrate the bin() function
number = 100
print('The binary equivalent of 100 is:', bin(number))
Output
The binary equivalent of 100 is: 0b1100100
Example 2: TypeError: ‘float’ object cannot be interpreted as an integer
# Python code to demonstrate the bin() function
number = 100.66
print('The binary equivalent of 100 is:', bin(number))
Output
raceback (most recent call last):
File "c:\Projects\Tryouts\main.py", line 3, in <module>
print('The binary equivalent of 100 is:', bin(number))
TypeError: 'float' object cannot be interpreted as an integer
Example 3: Convert an object to binary implementing __index__() method
In the below example, we are sending the TotalPrice class object to the bin() method.
The bin()
method does not raise an exception even if the argument passed is not of integer type since we have implemented the __index__()
method in our class, which always returns the positive integer.
# Python code to demonstrate the bin() function using __index__()
class TotalPrice:
apple = 100
orange = 50
watermelon=22
def __index__(self):
return self.apple + self.orange + self.watermelon
print('The binary equivalent of Total Price object is:', bin(TotalPrice()))
Output
The binary equivalent of Total Price object is: 0b10101100