View source code
Display the source code in std/math.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.math.isPowerOf2

Check whether a number is an integer power of two.

bool isPowerOf2(X) (
  const X x
) pure nothrow @nogc @safe
if (isNumeric!X);

Note that only positive numbers can be integer powers of two. This function always return false if x is negative or zero.

Parameters

NameDescription
x the number to test

Returns

true if x is an integer power of two.

Example

assert( isPowerOf2(1.0L));
assert( isPowerOf2(2.0L));
assert( isPowerOf2(0.5L));
assert( isPowerOf2(pow(2.0L, 96)));
assert( isPowerOf2(pow(2.0L, -77)));

assert(!isPowerOf2(-2.0L));
assert(!isPowerOf2(-0.5L));
assert(!isPowerOf2(0.0L));
assert(!isPowerOf2(4.315));
assert(!isPowerOf2(1.0L / 3.0L));

assert(!isPowerOf2(real.nan));
assert(!isPowerOf2(real.infinity));

Example

assert( isPowerOf2(1));
assert( isPowerOf2(2));
assert( isPowerOf2(1uL << 63));

assert(!isPowerOf2(-4));
assert(!isPowerOf2(0));
assert(!isPowerOf2(1337u));

Authors

Walter Bright, Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw and David Nadlinger

License

Boost License 1.0.