[math-fun] reversing the order of bits in a word
ulong jj3_revbin(ulong x) { ulong z; z = (x ^ (x >> 2)) & 0x9249249249249249UL; x ^= z ^ (z << 2); // low 3 bits reversed z = (x ^ (x >> 6)) & 0x01c0e070381c0e07UL; x ^= z ^ (z << 6); // low 9 bits reversed z = (x ^ (x >> 18)) & 0x00001ff0000001ffUL; x ^= z ^ (z << 18); // low 27 bits reversed z = (x ^ (x >> 36)) & 0x0000000007ffffffUL; x ^= z ^ (z << 36); // low 63 bits reversed x = (x>>63) | (x<<1); // rotate left by 1 return x; } Can explain if anybody is interested later, got a visitor now. Did run automated testing, but would appreciate independent "OK"s. Yes, tricky. Best, jj
* Joerg Arndt <arndt@jjj.de> [Apr 03. 2014 17:09]:
ulong jj3_revbin(ulong x) { ulong z; z = (x ^ (x >> 2)) & 0x9249249249249249UL; x ^= z ^ (z << 2); // low 3 bits reversed z = (x ^ (x >> 6)) & 0x01c0e070381c0e07UL; x ^= z ^ (z << 6); // low 9 bits reversed z = (x ^ (x >> 18)) & 0x00001ff0000001ffUL; x ^= z ^ (z << 18); // low 27 bits reversed z = (x ^ (x >> 36)) & 0x0000000007ffffffUL; x ^= z ^ (z << 36); // low 63 bits reversed x = (x>>63) | (x<<1); // rotate left by 1 return x; }
Can explain if anybody is interested later, got a visitor now. Did run automated testing, but would appreciate independent "OK"s. Yes, tricky.
Best, jj
Brrrr, version above reverses 63 bits and clears the highest, next reverses all 64 bits, highest bit in first mask dropped now: ulong jj3_revbin(ulong x) { ulong z; z = (x ^ (x >> 2)) & 0x1249249249249249UL; x ^= z ^ (z << 2); // ... rest as before ... }
participants (1)
-
Joerg Arndt