# Python Bin | Count total bits in a number

• Difficulty Level : Basic
• Last Updated : 31 Jan, 2023

Given a positive number n, count total bit in it.

Examples:

```Input : 13
Output : 4
Binary representation of 13 is 1101

Input  : 183
Output : 8

Input  : 4096
Output : 13```

We have existing solution for this problem please refer Count total bits in a number link.

Approach#1:  We can solve this problem quickly in Python using bin() function. Convert number into it’s binary using bin() function and remove starting two characters ‘0b’ of output binary string because bin function appends ‘0b’ as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number.

## Python3

 `# Function to count total bits in a number` `def` `countTotalBits(num):``    ` `     ``# convert number into it's binary and``     ``# remove first two characters .``     ``binary ``=` `bin``(num)[``2``:]``     ``print``(``len``(binary))` `# Driver program``if` `__name__ ``=``=` `"__main__"``:``    ``num ``=` `13``    ``countTotalBits(num)`

Output

`4`

Approach#2: We can solve this problem by simply using bit_length function of integer. This function returns the number of bits required to represent the number in binary form.

## Python3

 `# Function to count total bits in a number` `def` `countTotalBits(num):``    ` `     ``# bit_length function return``     ``# total bits in number``     ``B_len ``=` `num.bit_length()``     ``print``(``"Total bits in binary are : "``, B_len)` `# Driver program``if` `__name__ ``=``=` `"__main__"``:``    ``num ``=` `13``    ``countTotalBits(num)`

Output

`Total bits in binary are :  4`

My Personal Notes arrow_drop_up