# finding closest lower power of two of a integer number

This topic is 1650 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites

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:

##### Share on other sites
Yet another implementation, if you are using gcc:

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