30

I'm working on a programming project and one of things I need to do is write a function that returns a mask that marks the value of the least significant 1 bit. Any ideas on how I can determine the value using bitwise operators?

ex: 
0000 0000 0000 0000 0000 0000 0110 0000 = 96
What can I do with the # 96 to turn it into:
0000 0000 0000 0000 0000 0000 0010 0000 = 32

I've been slamming my head against the wall for hours trying to figure this out any help would be greatly appreciated!

Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81
Riptyde4
  • 5,134
  • 8
  • 30
  • 57

3 Answers3

60
x &= -x; /* clears all but the lowest bit of x */
R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
3

To be sure you get the right bit/value:

  • The value at the least significant bit position = x & 1
  • The value of the isolated least significant 1 = x & -x
  • The zero-based index of the isolated least significant 1 = log2(x & -x)

Here's how it looks in JavaScript:

let x = 0b1101000;

console.log(x & 1);            // 0 (the farthest-right bit)
console.log(x & -x);           // 8 (the farthest-right 1 by itself)
console.log(Math.log2(x & -x); // 3 (the zero-based index of the farthest-right 1)
Seth
  • 6,514
  • 5
  • 49
  • 58
2

A more readable code:

int leastSignificantBit(int number)
{
    int index = 0;

    while ((~number) & 1) {
        number >>= 1;
        index++;
    }
    return 1 << index;
}
Craig McQueen
  • 41,871
  • 30
  • 130
  • 181
MasterID
  • 1,510
  • 1
  • 11
  • 15
  • 16
    The text "a more readable code" is misleading. This is an alternate approach that performs an expensive operation (bit search, essentially a type of log) then inverts it to get the answer, rather than just computing the answer directly. – R.. GitHub STOP HELPING ICE Sep 14 '13 at 21:54
  • 2
    I understand. But this doesn't require knowledge about two's complement, this is why its "simpler". But I agree with you, it is much more expensive. – MasterID Sep 14 '13 at 22:01