Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting least significant bit in JavaScript

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?

like image 697
James Monger Avatar asked Nov 29 '22 14:11

James Monger


2 Answers

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;
like image 44
Barmar Avatar answered Dec 04 '22 21:12

Barmar


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
like image 70
Strikeskids Avatar answered Dec 04 '22 22:12

Strikeskids