Q:

Python | Count total number of bits in a number

belongs to collection: Python basic programs

0

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 

All Answers

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

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 

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

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Generate random number using numpy librar... >>
<< Python | Compute the net amount of a bank account ...