Python bin()

In this post, we will see about python bin() function.
Python bin() method converts an int to binary with ‘0b’ as prefix.If x is not an int then it needs to define __index__ method which returns an int.


Syntax

x is the int which you want to convert to binary.


Return

It returns binary representation of int.


Example

Let’s understand with help of simple example:

print('Binary representation of 9:',bin(9)) print('Binary representation of 13:',bin(13)) print('Binary representation of 101:',bin(101))

Output:

Binary representation of 9: 0b1001
Binary representation of 13: 0b1101
Binary representation of 101: 0b1100101

bin() for user defined class

You need to implement __index__() method which returns an int in case of user defined class.We are simply returning 9 from below __index__() and when you call bin(country), it internally executes __index__() of country class only.

class Country: name = 'India' population = 10000 def __index__(self): return 9 country = Country() print(bin(country))

Output:

0b1001

That’s all about Python bin function.

Leave a Reply

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