Python: Count total number of bits in a number

Include all outnumber of bits in a number in Python: A number is given and we need to see its complete number of bits as put away utilizing Python program.

Given a number and we need to discover a complete number of bits of paired an incentive to speak to the number utilizing 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

Program:

binary value of 61 is: 0b111101
total number of bits:  6

By characterizing capacity

In the beneath program, we utilized len(bin(n)[2:]), it will return all out the length of the paired an incentive 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 

Leave a Comment

error: Alert: Content is protected!!