power of 2

R

raghu

is it possible to write a code using bitwise operators for checking
whether a number is power of 2 or in general power of n
(n=2,3,4,...)??

Thanks a lot.

Regards,
Raghu
 
R

Richard Heathfield

raghu said:
is it possible to write a code using bitwise operators for checking
whether a number is power of 2
Yes.

or in general power of n
(n=2,3,4,...)??

Yes.
 
F

Frederick Gotham

raghu posted:
is it possible to write a code using bitwise operators for checking
whether a number is power of 2


There's a recent thread which counts the number of set bits in an integer
which would work for you, e.g.:

#define IS_POW_TWO(x) (1==QUANT_BITS((x)))

or in general power of n
(n=2,3,4,...)??


#define IS_POW_X(x,pow) (!((x)%(pow)))
 
S

Snis Pilbor

Frederick said:
raghu posted:



#define IS_POW_X(x,pow) (!((x)%(pow)))

No, this will check whether x is a multiple of pow. For example,
!(6%2) is true even though 6 is certainly not a power of 2.
 
R

Richard Heathfield

Frederick Gotham said:
raghu posted:



There's a recent thread which counts the number of set bits in an integer
which would work for you, e.g.:

#define IS_POW_TWO(x) (1==QUANT_BITS((x)))

There's an easier way.
#define IS_POW_X(x,pow) (!((x)%(pow)))

It doesn't use bitwise operators and doesn't check whether a number is a
power of n. Oops.
 
P

pete

raghu said:
is it possible to write a code using bitwise operators for checking
whether a number is power of 2 or in general power of n
(n=2,3,4,...)??

int n_is_Power_of_two(long unsigned n)
{
return (n & n - 1) == 0 && n != 0;
}

int n_is_Power_of_four(long unsigned n)
{
return (n & n - 1) == 0 && n % 3 == 1;
}

int n_is_Power_of_eight(long unsigned n)
{
return (n & n - 1) == 0 && n % 7 == 1;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,273
Latest member
DamonShoem

Latest Threads

Top