Python Bin | Count the total number of bits in a number

Python Methods and Functions


 Input: 13 Output: 4 Binary representation of 13 is 1001 Input: 183 Output: 8 Input: 4096 Output: 13 

We have solution to this problem, please refer to bin () function. Convert the number to binary using the bin () function and remove the leading two "0b" characters from the output binary string, because the bin function prefixes "0b" in the output string. Now print the length of the binary string, which will be the number of bits in the binary representation of the input number.

# Function for counting the total number of bits in a number


def countTotalBits (num):


# convert the number to binary and

  # remove the first two 0b characters.

binary = bin (num) [ 2 :]

print ( len (binary)) 

# Driver program

if __ name__ = = "__ main__" :

num = 13

  countTotalBits (num)