AppDividend
Latest Code Tutorials

Python bin Example | bin() Function In Python Tutorial

0

Python bin Example | bin() Function In Python Tutorial is today’s topic. Converting a decimal to binary is always an important function that is required in competitive programming as well. The bin() function returns a binary representation of an integer as the string. Using the bin() reduces the time required to code and also removes the hassle.

Python bin Example

See the Python bin() function syntax.

bin(number)

The function bin() takes the number as a parameter which is converted to the binary number. If the number is not an integer, then __index__() method is implemented to return the integer.

See the following code example.

print("Binary of Eleven is:", bin(11))

See the following output.

➜  pyt python3 app.py
Binary of Eleven is: 0b1011
➜  pyt

As you can see in the example above, the bin() function returns the equivalent binary number prefixed with 0b of an integer.

If you don’t want that prefixed 0b, you can use the format() function.

print(format(11, 'b'))

See the following output.

➜  pyt python3 app.py
1011
➜  pyt

#Convert an object to binary implementing __index__() method

See the following example in which we implement the object to the binary implementing __index__() method.

class Add:
    a = 11
    b = 19

    def __index__(self):
        return self.a + self.b


app = Add()
print('Equivalent binary number is:', bin(app))

See the following output.

➜  pyt python3 app.py
Equivalent binary number is: 0b11110
➜  pyt

That is how the __index__() function is used to return an integer when we don’t have an integer as an argument in the Python bin() function.

More Examples

See the following example.

a = 11
b = bin(a)
print(type(b))
print(bin(a))

See the output.

➜  pyt python3 app.py
<class 'str'>
0b1011
➜  pyt

The bin() method is available and compatible with both the Python version Python 2.x and 3.x.

#Python bin() with float

See the following code example of the bin() with the float.

a = 11.19
print(bin(a))

See the following output.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(bin(a))
TypeError: 'float' object cannot be interpreted as an integer
➜  pyt

So, Python bin() function can be used with the integers having different formats such as an octal, hexadecimal too. The function will take care of converting them into the binary string.

That’s all for python bin() function to convert an integer to the binary string. We also learned that an Object could also be converted to the binary string representation by implementing __index__() function that returns an integer.

Finally, Python bin Example | bin() Function In Python Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.