Count bits used in int

Posted by sigvardsen on Stack Overflow See other posts from Stack Overflow or by sigvardsen
Published on 2010-05-29T16:35:11Z Indexed on 2010/05/29 16:42 UTC
Read the original article Hit count: 282

Filed under:
|
|
|

If you have the binary number 10110 how can I get it to return 5? e.g a number that tells how many bits are used? There are some likewise examples listed below:

  • 101 should return 3
  • 000000011 should return 2
  • 11100 should return 5
  • 101010101 should return 9

How can this be obtained the easiest way in Java? I have come up with the following method but can i be done faster:

public static int getBitLength(int value)
{
    int l = 1;
    if (value >> 16 > 0)
    {
        value = value >> 16;
        l += 16;
    }
    if (value >> 8 > 0)
    {
        value = value >> 8;
        l += 8;
    }
    if (value >> 4 > 0)
    {
        value = value >> 4;
        l += 4;
    }
    if (value >> 2 > 0)
    {
        value = value >> 2;
        l += 2;
    }
    if (value >> 1 > 0)
    {
       value = value >> 1;
        l += 1;
    }
    return l;
}

© Stack Overflow or respective owner

Related posts about java

Related posts about math