Search code examples
c#integerbit-manipulationbit

Minimum number of bits to represent number


What is the most efficient way to find out how many bits are needed to represent some random int number? For example number 30,000 is represented binary with

111010100110000

So it needs 15 bits


Solution

  • int v = 30000; // 32-bit word to find the log base 2 of
    int r = 0; // r will be lg(v)
    
    while ( (v >>= 1) != 0) // unroll for more speed...
    {
      r++;
    }
    

    For more advanced methods, see here http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious

    Note that this computes the index of the leftmost set bit (14 for 30000). If you want the number of bits, just add 1.