Python bin()

Filed Under: Python

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.


x = 10
y = bin(x)
print(type(y))
print(bin(x))

Output:


<class 'str'>
0b1010

python bin

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.


x = 0b110 # 6
print(bin(x))

x = 0xF # 15
print(bin(x))

x = 0o70 # 56
print(bin(x))

Output:


0b110
0b1111
0b111000

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.


x = 10
print(format(x, '#b')) # 0b1010
print(format(x, 'b')) # 1010
x= 0xF
print(format(x, 'b')) # 1111
print(f'{x:b}') # 1111 (If you knew this format, you are Python Ninja!)

Output:


0b1010
1010
1111
1111

Python bin() with float

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


x = 10.5
print(bin(x))

Output:


TypeError: 'float' object cannot be interpreted as an integer

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.


class Person:
    id = 0
    def __init__(self, i):
        self.id = i

    def __index__(self):
        return self.id

p = Person(10)
print(bin(p))

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:


    def __index__(self):
        return str(self.id)

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

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages