c - An elegant way to find a power of 2 -


my question quite similar fastest way of computing power "power of 2" number used?:

giving x=2^y input want output y. difference i'm coding in c, not c++ , know sure there 1 bit set in input i'm wondering if there more efficient ways solve this.

here try:

unsigned int get_power_of_two(unsigned int x) {     unsigned int y=0;     for(unsigned int input=x; input>0; input=input>>1)     {         if(input & 1u)         {             break;         }         y++;     }     return y; } 

what efficiency compared proposed lookup table in @dave's answer ? (again, i'm coding in c don't have iterators functions lower_bound)

in case since know 1 bit set, it's enough count trailing zeros. can done without hardware instruction quickly. check out answer, that's code below comes (i'm not 1 tamper perfection... sometimes).

unsigned v;  // number 1 bit set unsigned r;  // becomes exponent in v == pow(2, r) static const unsigned multiplydebruijnbitposition[32] =  {   0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,    31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; r = multiplydebruijnbitposition[((unsigned)((v & -v) * 0x077cb531u)) >> 27]; 

in case since v has 1 bit set, don't need find lowest bit set; therefore can skip v & -v. , version of code becomes this:

unsigned v;  // number 1 bit set unsigned r;  // becomes exponent in v == pow(2, r) static const unsigned multiplydebruijnbitposition[32] =  {   0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,    31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; r = multiplydebruijnbitposition[(v * 0x077cb531u) >> 27]; 

see link more information, in turn links it's source information.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -