c++ - How to find n where k = 2^n -
this question has answer here:
- position of least significant bit set 21 answers
if know integer k = 2^n
, how can efficiently find n
? in other words, if know single bit in integer set, how can location of bit?
an idea find hamming weight of k-1
there other simpler ways i'm not thinking about?
bit twiddling hacks have lot of amazing (and obscure, performance oriented) bit hacks. best 1 use seems using multiply , lookup.
unsigned int v; // find number of trailing zeros in 32-bit v int r; // result goes here static const int 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[((uint32_t)((v & -v) * 0x077cb531u)) >> 27];
this page provides detailed analysis of problem focus on chess programming.
answer copied here. ps: didn't know how give credit author on question, , wrote this.
Comments
Post a Comment