Python bin() with Examples

Python bin() function is used to convert an integer into the binary format string. The formatted string is prefixed with “0b”.

Python bin()

Python bin() function can be used with integers having different formats such as octal, hexadecimal too. The function will take care of converting them into the binary string. Let’s look at some examples of bin() function.

Output:

From the output, it’s clear that the bin() function returns a string and not a number. Python type() function returns the type of the object.

Python bin() example with other format integers

Let’s see some examples of using bin() function with integers in different formats.

Output:

Tip: If you don’t want “0b” prefix in the binary string, you can also use format() function. Here is a quick example showing how to use format() function.

Output:

Python bin() with float

Let’s see what happens when we try to run bin() function with a float argument.

Output:

Python bin() with Object

If you want to have a binary string representation of an Object, then you will have to implement __index__() function that must return an integer. Let’s see this with a simple example.

Output: 0b1010

If the object doesn’t define __index__() function, we will get an error message as TypeError: 'Person' object cannot be interpreted as an integer.

Let’s see what happens if __index__() function returns non-int. Just change the index() function to following:

Error: TypeError: __index__ returned non-int (type str)

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

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: