最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

bit manipulation - Getting least significant bit in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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
  • 1 & 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
Add a comment  | 

4 Answers 4

Reset to default 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

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
发布评论

评论列表(0)

  1. 暂无评论