1

Possible Duplicate:
How to check if a number is a power of 2

How could I write a method that would return true if passed in the value 2, 4, 8, 32, 64, and so on?

Community
  • 1
  • 1
Tyler Petrochko
  • 2,611
  • 4
  • 24
  • 30

2 Answers2

14

This is probably the best way:

((value & -value) == value)
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

Might want to look at this if you need a fast algorithm:

http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two

mk12
  • 25,873
  • 32
  • 98
  • 137