-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Numericshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors
Milestone
Description
Introduce methods
Rationale and Usage
Checking if a number is a power of 2 is a relatively common operation. There's always the
(value & (value - 1)) == 0 && value != 0bit twiddle hack, but it is verbose, clunky, not immediately clear, not ideal performance wise, and requires remembering.
Introducing a simple API that is equivalent would be useful.
Proposed API
namespace System.Numerics
{
public static class BitOperations
{
public static bool IsPow2(int value);
public static bool IsPow2(uint value);
public static bool IsPow2(long value);
public static bool IsPow2(ulong value);
}
}Details
It uses a popcount operation where possible, else uses the bit twiddle hack.
Open Questions
-
Should we consider 0 a power of 2?
- The classic bit twiddle doesn't
-
Should we have methods for float/double (or even decimal)?
- With float/double you can compare the mantissa to 0.5 I believe, but it isn't really
"in character" with the rest ofBitOperations(which generally only supports integral types)
- With float/double you can compare the mantissa to 0.5 I believe, but it isn't really
Pull Request
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Numericshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors