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

Python example of int.bit_length() method: Here, we are going to learn how to find number of bits necessary to represent an integer in binary? Submitted by IncludeHelp, on April 16, 2019

Problem statement

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

Find number of bits necessary to represent an integer in binary

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

Consider the below example without sample input and output:

Input:
num = 67 #binary: 1000011

# function call
print(num.bit_length())

Output:
7

Python program 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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.