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)
}
This answer works because of the way two’s complement notation is designed.
First, an example. Assume we have 8-bit signed integers.
The bitwise and will give you
00010000as 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:
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.