Algorithm for finding the smallest power of two that's greater or equal to a given value

Posted by Boyan on Stack Overflow See other posts from Stack Overflow or by Boyan
Published on 2008-12-13T08:08:49Z Indexed on 2010/05/12 23:54 UTC
Read the original article Hit count: 392

Filed under:
|
|

I need to find the smallest power of two that's greater or equal to a given value. So far, I have this:

int value = 3221; // 3221 is just an example, could be any number
int result = 1;

while (result < value) result <<= 1;

It works fine, but feels kind of naive. Is there a better algorithm for that problem?

EDIT. There were some nice Assembler suggestions, so I'm adding those tags to the question.

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about c++