Last active
March 26, 2018 10:08
-
-
Save tamarous/caf422074af6366e08445b3a8faff64f to your computer and use it in GitHub Desktop.
Common bit operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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