Skip to content

Instantly share code, notes, and snippets.

@kevinmoran
Created February 1, 2023 12:31
Show Gist options
  • Save kevinmoran/a8b5d7376355bbcb828ed8eadc7c7c2d to your computer and use it in GitHub Desktop.
Save kevinmoran/a8b5d7376355bbcb828ed8eadc7c7c2d to your computer and use it in GitHub Desktop.
Bit Twiddling Tricks From Game Engine Gems 2
// 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