Last active
June 10, 2022 08:42
-
-
Save crozone/1d1468116ede32e35fe53a9784115ae4 to your computer and use it in GitHub Desktop.
Get next largest power of two
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
public static class IntExtensions | |
{ | |
public static uint GetNextPowerOfTwo(this uint input) | |
{ | |
--input; | |
input |= input >> 1; | |
input |= input >> 2; | |
input |= input >> 4; | |
input |= input >> 8; | |
input |= input >> 16; | |
return input + 1; | |
} | |
public static ulong GetNextPowerOfTwo(this ulong input) | |
{ | |
--input; | |
input |= input >> 1; | |
input |= input >> 2; | |
input |= input >> 4; | |
input |= input >> 8; | |
input |= input >> 16; | |
input |= input >> 32; | |
return input + 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has been made redundant by
System.Numerics.BitOperations.RoundUpToPowerOf2()
in .NET 6:https://docs.microsoft.com/en-us/dotnet/api/system.numerics.bitoperations.rounduptopowerof2?view=net-6.0#System_Numerics_BitOperations_RoundUpToPowerOf2_System_UInt64_