I am trying to get the least significant bit
of a number
in JavaScript.
I have the following code:
let lsb = (parseInt("110", 2) & 0xffff);
By my understanding, the least significant bit of 110 is 110 as it is the right-most set bit.
However, the code above returns '6', which is the total value of 110
and not the least significant bit
.
How can I get the least significant bit?
I am trying to get the least significant bit
of a number
in JavaScript.
I have the following code:
let lsb = (parseInt("110", 2) & 0xffff);
By my understanding, the least significant bit of 110 is 110 as it is the right-most set bit.
However, the code above returns '6', which is the total value of 110
and not the least significant bit
.
How can I get the least significant bit?
Share Improve this question edited Nov 10, 2017 at 16:19 cнŝdk 32.1k7 gold badges60 silver badges80 bronze badges asked Feb 4, 2016 at 0:13 James MongerJames Monger 10.7k8 gold badges64 silver badges99 bronze badges 1 |4 Answers
Reset to default 14I take you at your example that you are looking for the lowest set bit, not the least significant bit
What you're looking for is a bit of a bitwise hack.
We can do this with some exploitation of the way negative numbers are represented (two's complement)
var lowestSetBit = (value) & (-value)
If you are actually looking for the least significant bit, then you can just mask on that bit
var leastSignificantBit = value & 1
The least significant bit is the rightmost bit, not the rightmost bit that's set. To get that, AND with 1
.
let lsb = parseInt("110", 2) & 1;
https://en.wikipedia.org/wiki/Least_significant_bit:
least significant bit (LSB) is the bit position in a binary integer giving the units value, that is, determining whether the number is even or odd
So it's easy:
let lsb = parseInt("110", 2) & 1
or even this:
let lsb = parseInt("110", 2) % 2
Finding the least significant bit of a number can easily be done by:
someNumber & 1
or in your specific case:
let lsb = (parseInt("110", 2) & 1
This works by masking every bit with a zero except for the least significant bit, which is &'d with that 1.
For example, let's have our input number be 21
21 & 1
Is the same as:
10101
& 00001
-------
00001 // => returns 1 since the last bit is turned on
& 0xffff
is neither a way to get the lowest set bit nor the lsb. It's just completely unrelated to both of them. – user555045 Commented Feb 4, 2016 at 14:17