简体   繁体   中英

How to (a) extract and (b) remove bits from a 32-bit integer in JavaScript

So I am trying to follow the tutorials on BitMasks and Bit Manipulation I've seen like this but am not getting expected results.

var a = 0b11110000000000000000000000000000
var b = 0b10010000000000000000000000000000
var c = a & b
console.log(c.toString(2))
// ...

The AND operator will only put a one in every position where all arguments had a one.

expected  0b10010000000000000000000000000000
received -0b01110000000000000000000000000000

Here and other places show how to clear and set a single bit, but I am wondering about a range/span of bits.

  1. How do I select the set bits in the pattern 0b11110000000000000000000000000000 . So anything that has 0b101101010101... or any other first 6 digits would extract into a number like 0b1011010000... or 0b101101 , where either the number was a 6-bit number, or a 32-bit number with all the trailing rhs values set to 0. This way I can do a single check against an integer to check if it has a specific pattern.
  2. How to clear or remove those bits from the integer, so instead of ending up with the 6 lhs bits, I end up with the remaining 26 rhs bits.

I had the similar problem when I was trying to calculate color hex.

You can use >>> 0 to make the result unsigned, and then get its binary correctly.

See this answer for more explanation.

 var a = 0b11110000000000000000000000000000; var b = 0b10010000000000000000000000000000; var c = (a & b) >>> 0; console.log(c.toString(2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM