Created
February 1, 2023 12:31
-
-
Save kevinmoran/a8b5d7376355bbcb828ed8eadc7c7c2d to your computer and use it in GitHub Desktop.
Bit Twiddling Tricks From Game Engine Gems 2
This file contains 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
// https://twitter.com/EricLengyel/status/1620683606216835073 | |
int clearLowestSetBit(int x) | |
{ | |
return x & (x-1); | |
} | |
int setLowestUnsetBit(int x) | |
{ | |
return x | (x+1); | |
} | |
int setAllBitsToRightOfLowestSetBit(int x) | |
{ | |
return x | (x-1); | |
} | |
int clearAllBitsToRightOfLowestUnsetBit(int x) | |
{ | |
return x & (x+1); | |
} | |
int extractLowestSetBit(int x) | |
{ | |
return x & -x; | |
} | |
int extractLowestUnsetBit(int x) | |
{ | |
return ~x & (x+1); | |
} | |
int createMaskForBitsOtherThanLowestSetBit(int x) | |
{ | |
return ~x | (x-1); | |
} | |
int createMaskForBitsOtherThanLowestUnsetBit(int x) | |
{ | |
return x | ~(x+1); | |
} | |
int createMaskForBitsLeftOfAndIncludingLowestSetBit(int x) | |
{ | |
return x | -x; | |
} | |
int createMaskForBitsLeftOfLowestSetBit(int x) | |
{ | |
return x ^ -x; | |
} | |
int createMaskForBitsLeftOfAndIncludingLowestUnsetBit(int x) | |
{ | |
return ~x | (x+1); | |
} | |
int createMaskForBitsLeftOfLowestUnsetBit(int x) | |
{ | |
return ~x ^ (x+1); | |
} | |
int createMaskForBitRightOfAndIncludingLowestSetBit(int x) | |
{ | |
return x ^ (x-1); | |
} | |
int createMaskForBitRightOfLowestSetBit(int x) | |
{ | |
return ~x & (x-1); | |
} | |
int createMaskForBitRightOfAndIncludingLowestUnsetBit(int x) | |
{ | |
return x ^ (x+1); | |
} | |
int createMaskForBitRightOfLowestUnsetBit(int x) | |
{ | |
return x & (~x-1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment