Skip to content

Consider introducing BitOperations.IsPow2 or Math.IsPow2 #31297

@john-h-k

Description

@john-h-k

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 != 0

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

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 of BitOperations (which generally only supports integral types)

Pull Request

#36163

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Numericshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions