Last active
February 9, 2026 02:30
-
-
Save t-mat/aea7f699454b3a591e789c067ec2f396 to your computer and use it in GitHub Desktop.
[C++20] isPowerOfTwo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <bit> | |
| #include <concepts> | |
| #include <stdio.h> | |
| template <std::unsigned_integral T> | |
| inline bool isPowerOfTwo(T x) { | |
| return std::has_single_bit(x); | |
| } | |
| template <std::signed_integral T> | |
| inline bool isPowerOfTwo(T x) { | |
| return x > 0 && isPowerOfTwo(static_cast<std::make_unsigned<T>>(x)); | |
| } | |
| template <typename T> | |
| bool isPowerOfTwoNaive(T x) { | |
| if (x <= 0) { return false; } | |
| while (x > 1) { | |
| if (x % 2 != 0) { | |
| return false; | |
| } | |
| x /= 2; | |
| } | |
| return true; | |
| } | |
| int main() | |
| { | |
| int errorCount = 0; | |
| for (uint32_t i = 0; i < 65536; ++i) { | |
| const bool a = isPowerOfTwo(i); | |
| const bool b = isPowerOfTwoNaive(i); | |
| if (a != b) { | |
| errorCount += 1; | |
| printf("i = 0x%02x, isPowerOfTwo = %d, isPowerOfTwoNaive = %d\n", i, a, b); | |
| } | |
| } | |
| const bool ok = errorCount == 0; | |
| return ok ? EXIT_SUCCESS : EXIT_FAILURE; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment