Skip to content

Instantly share code, notes, and snippets.

@tamarous
Last active March 26, 2018 10:08
Show Gist options
  • Save tamarous/caf422074af6366e08445b3a8faff64f to your computer and use it in GitHub Desktop.
Save tamarous/caf422074af6366e08445b3a8faff64f to your computer and use it in GitHub Desktop.
Common bit operations
// Get the ith bit of num.
bool getBit(int num, int i) {
return (num & (1 << i)) != 0;
}
// Set the ith bit of num.
int setBit(int num, int i) {
return num | (1 << i);
}
// Clear the ith bit of num.
int clearBit(int num, int i) {
int mask = ~(1 << i);
return num & mask;
}
// Clear from the highest to the ith bit of num.
int clearBitsMSBthroughI(int num, int i) {
int mask = 1 << i - 1;
return num & maskl
}
// Clear from the ith to the lowest bit of num.
int clearBitsIthrough0(int num, int i) {
int mask = ~(1 << (i+1) - 1);
return mask & num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment