Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Last active February 1, 2023 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matu3ba/f41517a488a6ac4c56fd0eb9fc642386 to your computer and use it in GitHub Desktop.
Save matu3ba/f41517a488a6ac4c56fd0eb9fc642386 to your computer and use it in GitHub Desktop.
some more bit tricks

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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment