Python bin()

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
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Type()

Python type()

Table of Contents Hide type() Syntaxtype() Parameterstype() Return ValueDifference between type() function and isinstance() functionExample of isinstance() method in PythonExample 1: Finding the type of a Python objectExample 2: type()…
View Post