Assuming the input fits in a long
, if you don't care much about performance, use log2
to compute the logarithm in base 2 (then cast it to an int) per other answers. BTW your naive getN
is practically fast enough (but would loop indefinitely for a 0 input, you could limit that with for(i = 0; i<64; i++)
), and might even be faster than a log2
, and you could make it a static inline
function (in some header file).
If you are using GCC and if you know that the input is a power of 2 (so has exactly one bit set), you could use the faster __builtin_ffs
builtin (find first set bit).
If the number is very large, you want to do arbitrary precision arithmetic. Then use a library like GMPlib.