Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The most efficient way to test if a number is 2^n (i.e. 2,4,8,etc.) in C++20?

A handy method to verify if a number n is a power of two (like 2, 4, 8, etc.) is to use the following test:

bool test = n & (n - 1) == 0;

This operation can be very efficient because it only involves subtraction, a bitwise AND, and a comparison. If this expression is evaluated to true, then the number n is indeed a power of two.

Another method uses the std::popcount (population count) function, which is part of the C++20 standard library, for the test:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bool test = std::popcount(n) == 1; // (Since C++20)

This function counts the number of set bits (1s) in. If the hardware supports a popcount instruction (POPCNT), this function can be very fast.

In C++, you generally “pay for what you use”. For this test there is no use for counting.

What is the better method, in terms of CPU efficiency?

>Solution :

bool test = std::has_single_bit(n);

std::has_single_bit should be converted to the most efficient sequence for the current platform

template< class T >
constexpr bool has_single_bit( T x ) noexcept;

(since C++20)

Checks if x is an integral power of two.

This overload participates in overload resolution only if T is an unsigned integer type (that is, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, or an extended unsigned integer type).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading