Python bin() Function



The Python bin() function is a built-in function that is used to convert a given integer to its binary equivalent, which is represented as a string. The final result of this operation will always start with the prefix 0b which indicates that the result is in binary.

If the specified parameter of bin() function is not an integer object, we need to implement __index__() method which converts a numeric object to an integer object.

Syntax

Following is the syntax of the Python bin() function −

bin(i) 

Parameters

The Python bin() function accepts a single parameter −

  • i − This parameter represents an integer object.

Return Value

The Python bin() function returns a binary representation of the specified integer.

Examples

Here are some examples demonstrating the working of bin() function −

Example 1

The following example shows the basic usage of Python bin() function. Here we are creating an integer object and then applying the bin() function to convert it to binary form.

i = 12 
binaryRepr = bin(i)
print("The binary representation of given integer:", binaryRepr)

When we run above program, it produces following result −

The binary representation of given integer: 0b1100

Example 2

In the code below, we are illustrating how to omit the initial prefix (0b) from the result of bin operation.

i = 12 
binaryRepr = bin(i)
# Omiting the prefix 0b
output = binaryRepr[2:]
print("The binary representation of given integer:", output)

Following is an output of the above code −

The binary representation of given integer: 1100

Example 3

The code below demonstrates the working of bin() function with a negative integer object.

i = -14 
binaryRepr = bin(i)
print("The binary representation of given integer:", binaryRepr)

Output of the above code is as follows −

The binary representation of given integer: -0b1110

Example 4

In the following code, we are going to demonstrate how to use the __index__() and bin() methods together to convert id of an employee into its binary representation.

class Id:
   emp_id = 121
   def __index__(self):
      return self.emp_id

binaryRepr = bin(Id())
print("The binary representation of given employee ID:", binaryRepr)

Following is an output of the above code −

The binary representation of given employee ID: 0b1111001
python_built_in_functions.htm
Advertisements