Skip to content

Instantly share code, notes, and snippets.

@lzhoucs
Last active November 6, 2015 06:55
Show Gist options
  • Save lzhoucs/aa021fe8608e88db72c5 to your computer and use it in GitHub Desktop.
Save lzhoucs/aa021fe8608e88db72c5 to your computer and use it in GitHub Desktop.
bit manipulation tricks
  • drop the first bit
x >> 1;
  • drop LSB (the least Significant bit)
x & (x - 1);
  • extracts the lowest set bit of x (all other bits are cleared)
x & !(x - 1);
  • extracts i-th bit
(x >>> i) & 1;
  • flip bit value
x ^= 1;
  • extracts part of bits from x using bit mask
// e.g : extract the 2nd 2 bytes (16 bits) from long x
x = x >> 16; // step 1. get rid of unwanted part (the first 2 bytes)
x = x & 0xFFFF; // step 2. extract only the bit mask number of bits, in this case, the bit mask is 16 bits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment