I've been looking around for an answer to this, but haven't found any decent solutions. I'm trying to convert a single-enabled-bit (32-bit mask) into its corresponding index location. The mask has only one bit enabled, from bit 0 to bit 31.
So here are the conversions I'm looking for: 1=1, 2=2, 4=3, 8=4, 16=5, 32=6, etc..
I'm not against making a lookup table, if the table isn't both terribly large and mostly empty. Is there any clever math out there to accomplish this in one step (without looping through the bits)?
EDIT: I could not find a satisfactory answer in the link provided. But after goofing around with some numbers, I did stumble onto a magic value that separates power of two values perfectly for 32 bit masks. That value is 37. If you modulate any 32-bit power of 2 value by 37, it will convert that power of two value into an index between 1 - 36. This means we can create a tiny lookup table of 37 values, with only a few entries wasted. Here is the fill rate of that table: |0|1|1|1|1|1|1|0|1|1|1|1|1|1|0|1|1|1|1|0|1|1|1|1|1|1|1|1|0|1|1|1|1|1|1|1|1|
I will mess around a little more to see if such a thing is possible with 64 bit values.
I don't understand why this forum is so quick to close topics. It makes it impossible to have any type of discussion about something that has been discussed before.