Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Innovative way for checking if number has only one on bit in signed int

Tags:

algorithm

byte

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) } 
like image 985
Meiscooldude Avatar asked Jul 01 '10 18:07

Meiscooldude


People also ask

How do you check if a bit is set to 1?

Below are simple steps to find the value of Kth bit: 1) Left shift given number 1 by k-1 to create a number that has only set bit as k-th bit. temp = 1 << (k-1) 2) If bitwise AND of n and temp is non-zero, then result is SET else result is NOT SET.

How do you know if two bits are set?

A simple solution is to traverse all bits. For every set bit, check if next bit is also set. An efficient solution is to shift number by 1 and then do bitwise AND. If bitwise AND is non-zero then there are two adjacent set bits.


1 Answers

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.

like image 71
MikeD Avatar answered Oct 12 '22 02:10

MikeD