finding closest lower power of two of a integer number

Started by
1 comment, last by alvaro 10 years, 8 months ago

Hi,

I wonder how could I find closest lower power of two to a given unsigned integer. The best way would be to get the bit position of most significant bit set. But how would I find it it with as few bitwise operations as possible? I must avoid any cycle, plus, I do not want to use the look up table as I find it uninteligent.

Advertisement

Have a look at this page for all sorts of bit twiddling stuff

http://graphics.stanford.edu/~seander/bithacks.html

You want to look at the section for this bit:

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
Yet another implementation, if you are using gcc:

unsigned round_down_to_power_of_2(unsigned x) {
  return 0x80000000u >> __builtin_clz(x);
}

This topic is closed to new replies.

Advertisement