Home » Python » Python programs

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

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

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.