Will
Will

Reputation: 549

Using bit operation to determine if a int is a power of 2

I once encountered a method of determining if a number x is a power of 2 by doing the following:

X&(x-1) followed by a 0 test, if the result is 0 then it means there is only one 1 bit in the number and that it is a power of 2. But the problem is it can't be used for signed int? I am just wondering if the only exception for a signed int is that it may be the signed bit that is the only one bit, if this is the case I could simply add another test and be done with it. Or does it have other exceptions that this method may not apply to a signed int. since I really wanna use it in java, I hope I can adopt it in some enhanced way. Thanks a lot.

Upvotes: 1

Views: 134

Answers (1)

Ry-
Ry-

Reputation: 224942

It doesn't matter; just test for negatives. A power of a positive number is never negative, so you can safely say that any negative number given isn't a power of two.

Upvotes: 2

Related Questions