C++ Bit Manipulation Check if an integer is a power of 2

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The n & (n - 1) trick (see Remove rightmost set bit) is also useful to determine if an integer is a power of 2:

bool power_of_2 = n && !(n & (n - 1));

Note that without the first part of the check (n &&), 0 is incorrectly considered a power of 2.



Got any C++ Question?