Q:

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

belongs to collection: Python miscellaneous programs

0

Given an integer number and we have to find necessary bits to represent it in binary in python.

To find necessary bits to represent a number – we use "bit_length()" method of "int" class, it is called with an integer object and returns the total number of bits to require to store/represent an integer number in binary.

Note: If the value is 0, bit_length() method returns 0.

Example:

    Input:
    num = 67 #binary: 1000011

    # function call
    print(num.bit_length())

    Output:
    7

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python code to find bits to represent 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python miscellaneous programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to print number of bits to store an... >>