LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

HOW TO KNOW IF A NUMBER IS A POWER OF TWO???

Hi!!

I have a little problem with CVI. I'm trying to check that a data
I read is a power of two or if it isn't but I don't know exactly how to do
this.
Is there any function that tells if a data is a power or two? I hope anybody
could help me!!

Thanks a lot!!
Bye!!
0 Kudos
Message 1 of 3
(3,052 Views)
You can use this:

#include
static double a, x;
static double intg, frac;
a = 144115188075855872.0;
x = log10 (a) / log10(2);
frac = modf (x, &intg);
if (frac == 0.0)
printf ("%.0fth power of 2\n", intg);
else
printf ("It is NOT a power of 2\n");

Theory:
if a is a power of 2, it is a=2^n
and also: log(a) = n * log(2)
so: log(a) / log(2) = n
and n is an integer value.

Regards
Roberto

"A. H." wrote:
>>>> Hi!!>> I have a little problem with CVI. I'm trying to check
that a data>I read is a power of two or if it isn't but I don't know exactly
how to do>this.>Is there any function that tells if a data is a power or
two? I hope anybody>could help me!!>> Thanks a lot!!> Bye!!
0 Kudos
Message 2 of 3
(3,052 Views)
"A. H." wrote:

> I have a little problem with CVI. I'm trying to check that a data
> I read is a power of two or if it isn't but I don't know exactly how to do
> this.
> Is there any function that tells if a data is a power or two? I hope anybody
> could help me!!

Here's how I would do it:
Advantages: All integer, no slow floating-point logarithms with their
round-off error poblemss. Theory: An integer is a power of two if it
has exactly one bit in its binary representation.

int isPowerOfTwo(int i) {
int sum;
for (sum=0; i>0; i>>=1) sum += i&1;
return sum==1;
}

Hope this helps!

- Rich
0 Kudos
Message 3 of 3
(3,052 Views)