Reputation: 5460
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
Reputation: 6832
To be sure you get the right bit/value:
x & 1
x & -x
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
Reputation: 1510
A more readable code:
int leastSignificantBit(int number)
{
int index = 0;
while ((~number) & 1) {
number >>= 1;
index++;
}
return 1 << index;
}
Upvotes: 2
Reputation: 215193
x &= -x; /* clears all but the lowest bit of x */
Upvotes: 61