Getting the least significant bit in JavaScript

I am trying to get the smallest value bitfor numberin javascript.

I have the following code:

let lsb = (parseInt("110", 2) & 0xffff);

In my opinion, the least significant bit 110 is 1 1 0, since this is the most significant bit.

However, the code above returns "6", which is a common value 110, not the least significant bit.

How can I get the least significant bit?

+4
source share
4 answers

The least significant bit is the rightmost bit, not the rightmost bit that is set. To get this, AND with 1.

let lsb = parseInt("110", 2) & 1;
+4

, ,

, , .

( )

var lowestSetBit = (value) & (-value)

,

var leastSignificantBit = value & 1
+7

https://en.wikipedia.org/wiki/Least_significant_bit:

(LSB) - , ,

:

let lsb = parseInt("110", 2) & 1

:

let lsb = parseInt("110", 2) % 2
+3

:

someNumber & 1

:

let lsb = (parseInt("110", 2) & 1

, , & 'd .

, 21

21 & 1

, :

  10101
& 00001 
-------
  00001 // => returns 1 since the last bit is turned on
+2
source

Source: https://habr.com/ru/post/1627229/


All Articles