Skip to content

Instantly share code, notes, and snippets.

@nadavmatalon
Last active October 25, 2016 14:13
Show Gist options
  • Save nadavmatalon/267ed2dc6381b794801dc2d5d40e381e to your computer and use it in GitHub Desktop.
Save nadavmatalon/267ed2dc6381b794801dc2d5d40e381e to your computer and use it in GitHub Desktop.
Bitmath Operations
// Source & much additional info:
// http://playground.arduino.cc/Code/BitMath
y = (x >> n) & 1; // n=0..7. stores nth bit of x in y. y becomes 0 or 1.
x &= ~(1 << n); // forces nth bit of x to be 0. all other bits left alone.
x &= (1<<(n+1))-1; // leaves alone the lowest n bits of x; all higher bits set to 0.
x |= (1 << n); // forces nth bit of x to be 1. all other bits left alone.
x ^= (1 << n); // toggles nth bit of x. all other bits left alone.
x = ~x; // toggles ALL the bits in x.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment