3 ms·
quote: "benaadams commented on 3 Oct • edited I couldn't believe there wasn't a number in the 2^64 space that did this. However, after exhaustive internet sear
by NKCSS 10y ago
quote:
"benaadams commented on 3 Oct • edited
I couldn't believe there wasn't a number in the 2^64 space that did this. However, after exhaustive internet searching I couldn't find one. So I went to sleep, woke up in the middle of the night with a headache and idea of a method to try and actually derived it.
Having derived it, I did some searching with the search engines and couldn't find any hits either in its decimal or hexadecimal from so called it Ben's Magic Number
I will write a blog post on the method I used."
Then:
"I tried to come up with a similar magic number that would allow to obtain the index after shifting its bits, and found a different one.
Wouldn't this number just do the same and be a bit easier to understand? 0x01020304050607
We know that after doing x=(v & (-v)) we get a power of 2, which when multiplied with the magic number will shift its bits by a multiple of 8 positions:
So after being multiplied by x, 0x0001020304050607 is turned into
0x0304050607000000 when shifted by a 3-byte offset
0x0405060700000000 when shifted by a 4-byte offset
0x0506070000000000 when shifted by a 5-byte offset
and so on...
We then simply have to read the 1st byte of the resulting number to find the offset, ie:
offset = (((v & -v) * Magic) >> 56) & 0x7"
Followed by:
"benaadams commented on 4 Oct • edited
@nicodeslandes Congats! That is a lot more obvious and what is happening; and drops a shift. Already superseded; that's the power of OSS collaboration!"
The comments here are very nice and worth a read.