tags:

views:

287

answers:

5

I'm looking for an innovative way to check if a number has only one on bit in a signed int.

I am well aware that I can simply do a loop with a counter, some modular division, and a bit shift. But I'm curious if there is a better way since we are only looking for ONE bit to be on.

bool HasOnlyOneBit (int  numb)
{
   //return true if numb has only one bit (I.E. is equal to 1, 2, 4, 8, 16... Int.MinValue)
}
+20  A: 
return x == (x & -x);

This answer works because of the way two's complement notation is designed.

First, an example. Assume we have 8-bit signed integers.

00010000  =  16
11110000  = -16

The bitwise and will give you 00010000 as a result, equal to your original value! The reason that this works is because when negating in 2's complement, first invert all the bits, then add 1. You'll have a bunch of zeros and a bunch of carries until a one falls into place. The bitwise and then checks if we have the right bit set.

In the case of a number that isn't a power of two:

  00101010  =  42
& 11010110  = -42
----------
  00000010 !=  42

Your result will still have only a single bit, but it won't match the original value. Therefore your original value had multiple bits set.

Note: This technique returns true for 0, which may or may not be desirable.

MikeD
Thanks a ton! Great response time too.
Meiscooldude
Thanks for the proofreading, Bill!
MikeD
You also need to test for `x > 0`, since this expression returns true for `x == 0`, but 0 is not a power of 2.
Paul R
+5  A: 

I'd recommend you take a look at the Bit Twiddling Hacks page and choose the most suitable option under "Determining if an integer is a power of 2" or "Counting bits set".

Kaleb Pederson
+14  A: 

This is a famous problem

(x & x-1) == 0

Power of 2 from Wiki : here

64 = 01000000 (x)
63 = 00111111 (x-1)
______________
&  = 00000000  == 0
______________ 

Case when some other bits are ON

18 = 00010010 (x)
17 = 00010001 (x-1)
______________
&  = 00010011  != 0
______________ 
Bragboy
@Bragboy take care of edge case where x!=0
yesraaj
@yesraaj : Taken care of
Bragboy
yesraaj
A: 

Take the log to base 2 of your number, if it's an integer your number has only 1 1 bit. Not sure that I think this is better than any of your excluded options.

High Performance Mark
+2  A: 

return (x && ((x & x-1) == 0))

srikfreak