I have a simple code to check if an INTEGER n is a power of 2
bool isPowerOfTwo(int n)
{
double x = log(n)/log(2);
return floor(x) == x ;
}
Most of the test cases are fine until n = 536870912 = 2^29.
In this case, the function return FALSE (which is not correct). I used printf to print floor(x) and x, both of them give 29.000000. But still, it returns FALSE. I hexdump x and floor(x)
x:
01 00 00 00 00 00 3D 40
floor(x):
00 00 00 00 00 00 3D 40
Why would floor(x) change a certain bit of x when x is a round number (29)? How to fix this problem ? Thanks in advance.
FYI:
- gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
- Target: x86_64-linux-gnu
EDIT: interestingly, if log() is replaced with log10(), it works fine.