The OpenD Programming Language

isPowerOf2

Check whether a number is an integer power of two.

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

pure @safe nothrow @nogc
bool
isPowerOf2
(
X
)
(
const X x
)

Parameters

x X

the number to test

Return Value

Type: bool

true if x is an integer power of two.

Examples

import std.math.exponential : pow;

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));
assert( isPowerOf2(1));
assert( isPowerOf2(2));
assert( isPowerOf2(1uL << 63));

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

Meta