Python program to find number of bits necessary to represent an integer in binary

Python example of int.bit_length() strategy: Here, we will figure out how to locate various bits important to speak to an integer in binary?

Given an integer number and we need to discover fundamental bits to speak to it in binary in python.

To discover fundamental bits to speak to a number – we use “bit_length()” strategy for “int” class, it is called with an integer article and returns the all outnumber of bits to require to store/speak to an integer number in binary.

Note: If the worth is 0, bit_length() strategy returns 0.

Example:

    Input:
    num = 67 #binary: 1000011

    # function call
    print(num.bit_length())

    Output:
    7

Python code to discover bits to speak to an integer number:

# Python program to find number of bits 
# necessary to represent an integer in binary

# input a number
num = int(input("Enter an integer number: "))

# total bits to represent number
bits = num.bit_length()

print("bits required to store ", num, " = ", bits)
print("binary value of ", num, " is = ", bin(num))

Output:

First run:
Enter an integer number: 67
bits required to store  67  =  7
binary value of  67  is =  0b1000011

Second run:
Enter an integer number: 3
bits required to store  3  =  2
binary value of  3  is =  0b11

Leave a Comment

error: Alert: Content is protected!!