Riptyde4
Riptyde4

Reputation: 5460

How can I get the value of the least significant bit in a number?

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!

Upvotes: 30

Views: 40744

Answers (3)

Seth
Seth

Reputation: 6832

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)

Upvotes: 3

MasterID
MasterID

Reputation: 1510

A more readable code:

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

    while ((~number) & 1) {
        number >>= 1;
        index++;
    }
    return 1 << index;
}

Upvotes: 2

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

x &= -x; /* clears all but the lowest bit of x */

Upvotes: 61

Related Questions