This is a detailed tutorial on the Python bin() Function. Learn to convert an integer or another Python Object to its binary equivalent string.
bin() built-in method is used to convert an integer into its binary equivalent. This method can also convert any other Python Object into its binary equivalent as well but for such a case, you need to make use of the
__index__() method additionally.
binaryEquivalent = bin(integerNumber)
bin() function takes only an integer number as the parameter. Providing any other data type except an integer will raise an error. You can also provide other python objects as the parameter but make sure that the class that belongs to that particular object should contain the
__index__() method that returns an integer value.
This way, whenever the object whose class contains the
__index__() method returning an integer will be provided as an argument, actually, the integer value returned is passed as the argument.
The error that is being raised if the provided argument is not a valid integer is a TypeError exception that will state that the provided argument type is not interpreted as an integer.
bin() Return Value
This method returns the binary equivalent of the provided integer as the argument. If the provided integer is another Python object than the integer, then it returns the binary equivalent of the returned integer value by the
__index__() method of the class of that object.
The first example simply converts an integer into its binary equivalent using the
bin() method while the second example illustrates the concept of using the
__index__() method to return an integer value for a particular python class and object.
Example 1. Integer Number To Binary Conversion
givenInteger = 52 binaryEquivalent = bin(givenInteger) print(binaryEquivalent)
The above code snippet illustrates the conversion of the binary number
52 into its binary equivalent string.
Example 2. Python Objects To Binary Conversion using __index__() Method
class TotalMarks: physics = 99 chemistry = 98 mathematics = 100 def __index__(this): return this.physics + this.chemistry + this.mathematics print(TotalMarks()) print(bin(TotalMarks()))
In the above code snippet, we’ve defined a class TotalMarks and then inside this class, we’ve defined the
__index__() method and it returns an integer which is simply the total of all of the subjects marks.
Then I first used the
print() statement to show that the
TotalMarks() is an object and then we’re passing this as an argument to the
I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.