How do I determine which bit is set in an unsigned int64
bit-manipulation, delphi
Solution
Finding the first bit set is the same as counting the zero bits, so this hack might help. That's a really useful page to bookmark, by the way.
Problem
I have a variable vBit which is an unsigned int64. I know there is exactly one bit set, and I need to figure out which one it is. Currently I do it like this (in Delphi): ``` vPos := -1; repeat vBit := vBit shr 1; inc(vPos); until vBit = 0; ``` Is there a faster way? All bit positions are equally likely, so on average the algorithm needs to iterate 32 times. I am looking for an elegant trick with ands and xors and whatnot.