Python bin() Method

Python bin() method converts a given integer to it’s equivalent binary string. If the method parameter is some other object (not integer) then it has to __index__() method (with double underscores on the both sides) which must return an integer value for the object.

The prefix 0b represents that a given string is a binary string.

1. Syntax

The syntax of bin() method is:

binaryString = bin( intValue );

Method parameters

This method takes single required parameter intValue of int datatype whose binary equivalent is to be calculated.

If parameter is not an int type, parameter object should implement __index__() method which should return an integer.

Method return Value

The return value is the binary string equivalent to the given integer.

TypeError

If the method parameter is not an integer, bin() raises a TypeError exception with message that the type cannot be interpreted as an integer.

2. Converting an integer to binary string

Python program to convert an integer to binary string using the bin() method.

intValue = 10
print('The binary string of 10 is:', bin(intValue))

intValue = -10
print('The binary string of -10 is:', bin(intValue))

names = ['Lokesh', "Alex"]
print('The binary equivalent of names list is:', bin(names))

Program output.

The binary string of 10 is:   0b1010
The binary string of -10 is: -0b1010
TypeError: 'list' object cannot be interpreted as an integer

3. Converting an object implementing __index__() method

Python program to convert an abject to binary string.The object implements __index__() method.

class Employee:
    id = 10
    age = 28
    name = 'Lokesh'
    
    def __index__(self):
        return self.id
        
print('The binary equivalent is:', bin(Employee()))

Program output.

The binary equivalent of quantity is: 0b1010

4. Removing “0b” prefix

To remove the prefixed “0b” string, use array slicing on the string.

intValue = 10
print('The binary string of 10 is:', bin(intValue)[2:])

Program output.

The binary string of 10 is:  1010

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode