I have the following C program:
#include <stdio.h>
#include <math.h>
#define LOG2(x) ((int)( log((double)(x)) / log(2) ))
int main() {
int num = 64;
int val1 = LOG2(num);
int val2 = LOG2(64);
printf("val1: %d, val2 %d\n", val1, val2);
return 0;
}
Which outputs:
val1: 5, val2: 6
Why does this macro produce a different (and wrong) answer when I use it with a variable, but works correctly when I just type 64 directly?
Regardless of whether or not this is actually a good way to get the log base 2, what is causing this behavior? Is there any way I can get this macro to work properly with variables? (all my inputs will be exact powers of 2)