Count total bits in a number - GeeksforGeeks

12 Jan, 2022
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
 
 
Method 1 (Using Log)
The log2(n) logarithm in base 2 of n, which is the exponent to which 2 is raised to get n only integer and we add 1 find total bit in a number in log(n) time. 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find total bit in given number#include <iostream>   #include <cmath> unsigned countBits(unsigned int number){          // log function in base 2    // take only integer part    return (int)log2(number)+1;} // Driven program   int main(){    unsigned int num = 65;    std::cout<<countBits(num)<<'\n';    return 0;} // This code is contributed by thedev05.
// C program to find total bit in given number#include <stdio.h>     #include <math.h> unsigned countBits(unsigned int number){           // log function in base 2      // take only integer part      return (int)log2(number)+1;} // Driven program      int main(){    unsigned int num = 65;    printf("%d\n", countBits(num));    return 0;}
// Java program to// find total bit// in given numberimport java.io.*; class GFG{    static int countBits(int number)    {                 // log function in base 2        // take only integer part        return (int)(Math.log(number) /                     Math.log(2) + 1);    }         // Driver code    public static void main (String[] args)    {        int num = 65;                 System.out.println(countBits(num));                                     }} // This code is contributed by vij
# Python3 program to find# total bit in given numberimport mathdef countBits(number):         # log function in base 2    # take only integer part    return int((math.log(number) /                math.log(2)) + 1); # Driver Codenum = 65;print(countBits(num)); # This code is contributed by mits
// C# program to find total bit// in given numberusing System; class GFG {         static uint countBits(uint number)    {                     // log function in base 2        // take only integer part        return (uint)Math.Log(number , 2.0) + 1;    }         // Driver code    public static void Main()    {        uint num = 65;                 Console.WriteLine(countBits(num));                                     }} // This code is contributed by Sam007.
<?php// PHP program to find total// bit in given number function countBits($number){         // log function in base 2    // take only integer part    return (int)(log($number) /                   log(2)) + 1;} // Driver Code$num = 65;echo(countBits($num)); // This code is contributed by Ajit.?>
<script>// JavaScript program to find total bit in given number     function countBits(number) {            // log function in base 2       // take only integer part      return Math.floor(Math.log2(number)+1);    }       // Driven program            let num = 65;    document.write(countBits(num));  // This code is contributed by Surbhi Tyagi</script>
7
 
Method 2 (Using Bit Traversal)
 
C
Java
Python3
C#
PHP
Javascript
/* Function to get no of bits in binary   representation of positive integer */#include <stdio.h>            unsigned int countBits(unsigned int n){   unsigned int count = 0;   while (n)   {        count++;        n >>= 1;    }    return count;}  /* Driver program*/int main(){    int i = 65;    printf("%d", countBits(i));    return 0;}
/* Function to get no of bits in binaryrepresentation of positive integer */class GFG {     static int countBits(int n)    {        int count = 0;        while (n != 0)        {            count++;            n >>= 1;        }                 return count;    }         /* Driver program*/    public static void main(String[] arg)    {        int i = 65;        System.out.print(countBits(i));    }} // This code is contributed by Smitha.
# Function to get no of bits# in binary representation# of positive integer def countBits(n):     count = 0    while (n):        count += 1        n >>= 1             return count # Driver programi = 65print(countBits(i)) # This code is contributed# by Smitha
/* Function to get no of bitsin binary representation ofpositive integer */using System; class GFG{    static int countBits(int n)    {        int count = 0;        while (n != 0)        {            count++;            n >>= 1;        }                 return count;    }         // Driver Code    static public void Main ()    {        int i = 65;        Console.Write(countBits(i));    }} // This code is contributed// by akt_mit.
<?php// PHP Code to get no of bits in binary// representation of positive integer // Function to get no of bits in binary// representation of positive integerfunction countBits($n){    $count = 0;    while ($n)    {        $count++;        $n >>= 1;    }    return $count;} // Driver Code$i = 65;echo(countBits($i)); // This code is contributed by Ajit.?>
<script> /* Function to get no of bitsin binary representation ofpositive integer */function countBits(n){    var count = 0;    while (n != 0)    {        count++;        n >>= 1;    }         return count;} // Driver Codevar i = 65;document.write(countBits(i)); </script>
7
Method 3 ( Using conversion from binary to string)
Python3
# function to count the number of bits in a number ndef count_bits(n):  # bin(n) returns a binary string representation of n preceded by '0b' in python  binary = bin(n)     # we did -2 from length of binary string to ignore '0b'  return len(binary)-2 a = 65b = 183 print(f"Total bits in {a}: {count_bits(a)}")print(f"Total bits in {b}: {count_bits(b)}") # This code is contributed by udit
Total bits : 7
Total bits : 8
 
YouTubeGeeksforGeeks500K subscribersCount total bits in a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OIOJRd6ca2g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Gyayak Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
Sam007
Smitha Dinesh Semwal
Mahadev99
Mithun Kumar
shaktipravesh
surbhityagi15
rutvik_56
thedev05
harshitchandani
uditkuma01
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Find the element that appears once
Bits manipulation (Important tactics)
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
C++ bitset and its application
Write an Efficient C Program to Reverse Bits of a Number
Check whether K-th bit is set or not