bin() function in Python
Introduction
The bin()
function converts and returns the binary equivalent string of a given integer. If the parameter isn't an integer, it has to implement __index__()
method to return an integer.
The syntax of bin()
method is:
bin(num)
where num is an integer number whose binary equivalent is to be calculated.
Note: In Python, a binary number is represented as a string prefixed with 0b.
Case 1: Integer to Binary
num = 3
print(bin(num))
Output:
0b11
Case 2: Object to Binary
In the case of Objects, we need to implement the __index__()
method to get the binary equivalent string for an object.
class Money:
ten_rupee_note = 3
fifty_rupee_note = 5
hundred_rupee_note = 7
def __index__(self):
return (10*self.ten_rupee_note) + (50*self.fifty_rupee_note) + (100*self.hundred_rupee_note)
money = Money()
print(f"Total Money: {money.__index__()}")
print(f"Total Money in Binary: {bin(money)}")
Output:
Total Money: 980
Total Money in Binary: 0b1111010100
Here, we've created a Money class with three attributes - ten_rupee_note
, fifty_rupee_note
, and hundred_rupee_note
. The __index__()
method returns the total money, i.e. the sum of notes multiplied with their respective valuation. We then pass an object of the Money class to the binary function which returns the binary equivalent string of the integer returned by the __index__()
method.
Case 3: Raises Exception
class Money:
ten_rupee_note = 3
fifty_rupee_note = 5
hundred_rupee_note = 7
money = Money()
print(f"Total Money in Binary: {bin(money)}")
In the previous example, if we don't implement the __index__()
method, we'll get a TypeError.
Output:
Traceback (most recent call last):
File "D:\Quarantine\Test\Blog-Codes\Built-Ins\bin\error.py", line 8, in <module>
print(f"Total Money in Binary: {bin(money)}")
TypeError: 'Money' object cannot be interpreted as an integer
Conclusion
In this part, we learned about the Python bin()
function with the help of examples. You can check out this tool to convert to binary.