Python | Count total number of bits in a number

In this example, we will learn how to count total number of bits in a number using Python program? By IncludeHelp Last updated : April 14, 2023

Prerequisite: Binary number systems in Python

Problem Statement

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 

Python code to count total number of bits in a number

# 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

Python code to count total number of bits in a number by defining own function

# 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 

Python Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





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