4

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?

1
  • 1
    & 0xffff is neither a way to get the lowest set bit nor the lsb. It's just completely unrelated to both of them. Commented Feb 4, 2016 at 14:17

4 Answers 4

14

I 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
Sign up to request clarification or add additional context in comments.

2 Comments

lowestSetBit was extremely useful for me. Much faster than unrolling and quite elegant. Not a chance I would have thought of this on my own.
I believe lowestSetBit will return value instead of the bit.
5

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;

1 Comment

Thanks, I was misunderstanding the meaning of the least significant bit.
3

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

3 Comments

You're missing the input radix 2.
The part of his original code that parses the integer uses base 2, so I think that's clear.
Why would he intentionally give the second argument to parseInt if that wasn't what he intended? Anyway, you believe what you want.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.