New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Consider introducing BitOperations.IsPow2 or Math.IsPow2 #31297
Comments
What about other types: signed integers and even floats (e.g. |
Even if the JIT can be "taught" that People shouldn't necessarily be expected to remember every "bit-twiddling hack" (although http://graphics.stanford.edu/~seander/bithacks.html is a good reference for them). There are also a lot of patterns and which are easiest to recognize by the JIT vs which actually perform the best is a constantly moving target. So, exposing a "helper" method on |
signed integers can be done simply by adding a check the number isn't floating points can be done by extracting exponent (preserving sign) and comparing it to 0.5, i think |
In addition to an expansion of per-primitive I have part of a prototype I can show if there's interest. |
@john-h-k, could you clean up the initial proposal just a bit and then I can mark this Ideally this would loosely follow the "good example" listed under step 1 of our API Review Process. Not all sections are needed, but providing the rationale and proposed API sections help ensure the review proocess flows more smoothly and the request is immediately obvious. I believe the proposed location should be |
👍 Done |
Thanks! As to the pending questions.
I think this would be fine for
No for integrals. For floating-point the question is a bit more complicated as |
Looks good as proposed 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);
}
} |
@terrajobst Note that a similar method on the |
That was also noted in API review. |
Introduce methods
Rationale and Usage
Checking if a number is a power of 2 is a relatively common operation. There's always the
bit 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
Details
It uses a popcount operation where possible, else uses the bit twiddle hack.
Open Questions
Should we consider 0 a power of 2?
Should we have methods for float/double (or even decimal)?
"in character" with the rest of
BitOperations
(which generally only supports integral types)Pull Request
#36163
The text was updated successfully, but these errors were encountered: