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,531
  • 4
  • 22
  • 30

2 Answers2

15

This is probably the best way:

((value & -value) == value)
David Schwartz
  • 173,634
  • 17
  • 200
  • 267
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,294
  • 29
  • 95
  • 136