Skip to content

Instantly share code, notes, and snippets.

Created October 10, 2015 18:05
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 anonymous/e2a398d6219ea9e26a7a to your computer and use it in GitHub Desktop.
Save anonymous/e2a398d6219ea9e26a7a to your computer and use it in GitHub Desktop.
Bang
/*
* bang - Compute !x without using !
* Examples: bang(3) = 0, bang(0) = 1
* Legal ops: ~ & ^ | + << >>
* Max ops: 12
* Rating: 4
*
* Use lots of bit-ands to duplicate any 1-bits across bytes, then across bits in the last byte
*/
int bang(int x) {
x = x | (x >> 16); // Now the least-significant byte pair has duplicates of any 1-bits in either byte pair
x = x | (x >> 8); // Same thing, but by byte
x = x | (x >> 4); // Same but by nibble
x = x | (x >> 2); // Now the least-significant pair of bits has 1-bits if any pair in the original x had 1-bits
x = x | (x >> 1); // The least-significant bit is on if any bits were on in x
return ~x & 0x1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment