424,964 Members | 1,290 Online Need help? Post your question and get tips & solutions from a community of 424,964 IT Pros & Developers. It's quick & easy.

power of 2

 P: n/a 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 Sep 14 '06 #1
6 Replies

 P: n/a 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. -- Richard Heathfield "Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk email: rjh at above domain (but drop the www, obviously) Sep 14 '06 #2

 P: n/a 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))) -- Frederick Gotham Sep 14 '06 #3

 P: n/a Frederick Gotham wrote: raghu posted: is it possible to write a code using bitwise operators for checking whether (snip) or in general power of n (n=2,3,4,...)?? #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. Sep 14 '06 #4

 P: n/a Frederick Gotham said: raghu posted: >is it possible to write a code using bitwise operators for checkingwhether 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))) There's an easier way. > or in general power of n(n=2,3,4,...)?? #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. -- Richard Heathfield "Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk email: rjh at above domain (but drop the www, obviously) Sep 14 '06 #5

 P: n/a raghu wrote: > 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; } -- pete Sep 14 '06 #6

 P: n/a In general, for bit twiddling: http://graphics.stanford.edu/~seander/bithacks.html Which has this (for instance): http://graphics.stanford.edu/~seande...mineIfPowerOf2 Which is Pete's solution. Another good source for interesting things like this is hackmem: http://www.inwap.com/pdp10/hbaker/hakmem/hakmem.html Sep 15 '06 #7 