Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created March 15, 2024 12:22
Show Gist options
  • Save unitycoder/78e6c1dead5dc22dca062f71397ebb59 to your computer and use it in GitHub Desktop.
Save unitycoder/78e6c1dead5dc22dca062f71397ebb59 to your computer and use it in GitHub Desktop.
NextPowerOfTwo, ClosestPowerOfTwo, IsPowerOfTwo
// https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Mathf.cs
public static int NextPowerOfTwo(int value)
{
value -= 1;
value |= value >> 16;
value |= value >> 8;
value |= value >> 4;
value |= value >> 2;
value |= value >> 1;
return value + 1;
}
public static int ClosestPowerOfTwo(int value)
{
int nextPower = NextPowerOfTwo(value);
int prevPower = nextPower >> 1;
if (value - prevPower < nextPower - value)
return prevPower;
else
return nextPower;
}
public static bool IsPowerOfTwo(int value)
{
return (value & (value - 1)) == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment