• Advertisement
Sign in to follow this  

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Yet another implementation, if you are using gcc:

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement