Alex Rivera | Logout

Find out number of bits needed to represent a positive integer in binary?

Asked 2009-03-25T02:20:49.347
34

This is probably pretty basic, but to save me an hour or so of grief can anyone tell me how you can work out the number of bits required to represent a given positive integer in Java?

e.g. I get a decimal 11, (1011). I need to get the answer, 4.

I figured if I could work out how to set all the bits other than the most significant bit to 0, and then >>> it, I'd get my answer. But... I can't.

Edit
Report

1 Answer

31

Well, you can just count how many times you shift right before you're left with just zero:

int value = 11;
int count = 0;
while (value > 0) {
    count++;
    value = value >> 1;
}
answered 2009-03-25T02:26:43.907

Your Answer