Since integers are usually represented in binary form in computers, it is efficient to check if a given number is a power of two by checking if its
unsigned
representation has a single-bit set.
In C++ such check could be expressed as x & (x-1) == 0
. However, the intent of this expression is unclear. Furthermore, it
requires special care for the value 0
, which would pass the above check without having any bit set or being a power of two.
The std::has_single_bit
function template, introduced in C++20 that checks if an integer is a power of two, expresses the intent more
clearly.
This rule reports computations that could be replaced with std::has_single_bit
.
Noncompliant code example
void f(unsigned x) {
if ((x > 0) && !(x & (x-1))) { // Noncompliant
// Special algorithm for powers of 2
}
// Normal algorithm
}
Compliant solution
void f(unsigned x) {
if (std::has_single_bit(x)) {
// Special algorithm for powers of 2
}
// Normal algorithm
}