Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

9 Answers
karthikeya Boyini

First we input a number then convert this number into binary using bin() function and next remove first two character ‘0b’ of output string, next calculate the length of binary string.

Example

Input:200
Output:8

Explanation

Binary representation of 200 is 10010000

Algorithm

Step 1: input number.
Step 2: convert number into its binary using bin() function.
Step 3: remove first two characters ‘0b’ of output binary string because bin function appends ‘ob’ a prefix in output string.
Step 4: then calculate the length of the binary string.

Example Code

# Python program to count total bits in a number
def totalbits(n):
   binumber = bin(n)[2:]
   print("TOTAL BITS ::>",len(binumber)) 
# Driver program
if __name__ == "__main__":
   n=int(input("Enter Number ::>"))
   totalbits(n)

Output

Enter Number ::>200
TOTAL BITS ::> 8

Arnab Chakraborty

Example
def bitsCount(n):
   count = 0
      while (n>0):
      count += 1
         n >>= 1
   return count
i = 4
print(bitsCount(i))

Output

3
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.