Why is this an issue?
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 to take special care for the value 0
, which would pass the above check, while not having any bit set and not being a power of
two.
This check can be expressed more clearly with the std::has_single_bit
function template, introduced in C++20.
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
}