Home »
Python
Python | Count total number of bits in a number
Count total number of bits in a number in Python: A number is given and we have to find its total number of bits to be stored using Python program.
Submitted by IncludeHelp, on September 05, 2018
Prerequisite: Binary number systems in Python
Given a number and we have to find total number of bits of binary value to represent the number using Python.
Example:
Input:
num = 61
Binary value of 61 is = 0b111101
Output:
Total number of bits = 6
Note: '0b' is prefixed to represent binary value
Input:
num = 12
Binary value of 61 is = 0b1100
Output:
Total number of bits = 4
Program:
# count total number of bits in a number
# declare a number
num = 61
# use bin () method to get the binary value of a number
# print binary value output will be 0b111101
print "binary value of {0} is: {1}".format (num, bin(num))
# store the length of the binary number
length = len(bin(num))
# since binary value contains 0b as prefix
# so to get exact length total number of bits
# subtract 2 from the length
length -=2
# print length
print "total number of bits: ", length
Output
binary value of 61 is: 0b111101
total number of bits: 6
By defining function
In the below program, we used len(bin(n)[2:]), it will return total length of the binary value after 2 characters.
Let’s understand
a=61
= len(bin(a)[2:]) # bin(a) is '0b111101'
= len('0b111101'[2:])
= len ('111101')
= 6
Program:
# count total number of bits in a number
# function to get total bits
# function will return total nember of bits
def totalBits(n):
return len(bin(n)[2: ])
#main code
a = 61
b = 12
print "Total bits in {0} = {1} ".format(a,totalBits(a))
print "Total bits in {0} = {1} ".format(b,totalBits(b))
Output
Total bits in 61 = 6
Total bits in 12 = 4
TOP Interview Coding Problems/Challenges