Open In App

bin() in Python

Improve
Improve
Like Article
Like
Save
Share
Report

Python bin() function returns the binary string of a given integer. bin() function is used to convert integer to binary string. In this article, we will learn more about Python bin() function.

Example

In this example, we are using the bin() function to convert integer to binary string.

Python3




x = bin(42)
print(x)


Output

0b101010

Python bin() function Syntax

The bin() function in Python has the following syntax:

Syntax:  bin(a)

Parameters : a : an integer to convert

Return Value : A binary string of an integer or int object.

Exceptions : Raises TypeError when a float value is sent in arguments.

bin() in Python Examples

Let us see a few examples of the bin() function in Python for a better understanding.

Convert Integer to Binary String

In this example, we simply passed an integer to the bin() function, which allows you to convert integer to a binary string, returning the binary representation of that number.

Python3




# Python code to demonstrate working of
# bin()
 
# declare variable
num = 100
 
# print binary number
print(bin(num))


Output

0b1100100

Convert integer to binary with a user-defined function

In this example, we created a user-defined function that takes an integer as the parameter and returns the binary representation of the number as a binary string, effectively convert the integer to a binary string after removing the ‘0b’ characters that indicate that a number is in binary format.

Python3




# Python code to demonstrate working of
# bin()
 
# function returning binary string
def Binary(n):
    s = bin(n)
 
    # removing "0b" prefix
    s1 = s[2:]
    return s1
 
print("The binary representation of 100 (using bin()) is : ", end="")
print(Binary(100))


Output

The binary representation of 100 (using bin()) is : 1100100

User-defined object to binary using bin() and __index()__

Here we send the object of the class to the bin methods, and we are using Python special methods __index()__ method which always returns a positive integer, and it can not be a rising error if the value is not an integer. 

Python3




# Python code to demonstrate working of
# bin()
class number:
    num = 100
 
    def __index__(self):
        return(self.num)
 
print(bin(number()))


Output

0b1100100


Last Updated : 15 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads