Assuming MIN < x < MAX:
trick | operation/effect | note |
---|---|---|
x & (x - 1) |
clear lowest 1 bit | if result 0, then x is 2 |
`x | (x + 1)` | set lowest 0 bit |
`x | (x - 1)` | set all bits to right of lowest 1 bit |
x & (x + 1) |
clear all bits to right of lowest 0 bit | |
x & -x |
extract lowest 1 bit | |
~x & (x + 1) |
extract lowest 0 bit (as 1 bit) | |
~x & (x - 1) |
create mask for bits othern than lowest 1 bit | |
`x | ~(x + 1)` | create mask for bits other than lowest 0 bit |
`x | -x` | cr mask for bits left of lowest 1 bit. inclusive |
x ^ -x |
cr mask for bits left of lowest 1 bit. exclusive | -x must never underflow |
`~x | (x + 1)` | cr mask for bits left of lowest 0 bit. inclusive |
~x ^ (x + 1) |
cr mask for bits left of lowest 0 bit. exclusive | also x equivalent to x + 1 |
x ^ (x - 1) |
cr mask for bits right of lowest 1 bit. inclusive | 0 becomes -1 |
~x & (x - 1) |
cr mask for bits right of lowest 1 bit. exclusive | 0 becomes -1 |
x ^ (x + 1) |
cr mask for bits right of lowest 0 bit. inclusive | -1 remains -1 |
x &(~x - 1) |
cr mask for bits right of lowest 0 bit. exclusive | -1 remains -1 |