Last active
May 21, 2016 16:58
-
-
Save zapstar/1dc061a412b44908c86b1b75c18b04ab to your computer and use it in GitHub Desktop.
Bit Hacks
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
/** | |
* Bit hacks | |
* | |
* Not as extensive as https://graphics.stanford.edu/~seander/bithacks.html | |
* but I want a quick reference for myself | |
*/ | |
// multiply x by 2^n | |
int mul_pow2(int x, int n) { | |
return x << n; | |
} | |
// divide x by 2^n | |
int div_pow2(int x, int n) { | |
return x >> n; | |
} | |
// set jth bit | |
int set_bit(int x, int j) { | |
return x | (1 << j); | |
} | |
// check if jth bit is set | |
bool is_bit_set(int x, int j) { | |
return (x & (1 << j)) != 0; | |
} | |
// unset jth bit | |
int unset_bit(int x, int j) { | |
return x & ~(1 << j); | |
} | |
// flip jth bit | |
int flip_bit(int x, int j) { | |
return x ^ (1 << j); | |
} | |
// get the lowest bit set | |
int lowest_bit(int x) { | |
return x & -x; | |
} | |
// get the highest bit set | |
int highest_bit(int x) { | |
x |= (x >> 1); | |
x |= (x >> 2); | |
x |= (x >> 4); | |
x |= (x >> 8); | |
x |= (x >> 16); | |
return x ^ (x >> 1); | |
// can also return x - (x >> 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment