Created
March 15, 2024 12:22
-
-
Save unitycoder/78e6c1dead5dc22dca062f71397ebb59 to your computer and use it in GitHub Desktop.
NextPowerOfTwo, ClosestPowerOfTwo, IsPowerOfTwo
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://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