-1

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.
Lance
  • 75,200
  • 93
  • 289
  • 503
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers – jonrsharpe Dec 10 '19 at 10:17
  • 1
    The problem is again JS' ambiguity. Like JS' handling of strings and numbers, and the often (but not always) interchangability, you also have this with numbers. JS' bit operations are performed on (and return) 32-bit **signed** integers. `0b11110000000000000000000000000000` is parsed as the number `4026531840` which is too big for an int. This is a double, and the corresponding int is `-268435456`. You get that, when you do `0b1111<<28` for example, or using `const int = v => v|0`. – Thomas Dec 10 '19 at 11:10

1 Answers1

1

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));
Hao Wu
  • 17,573
  • 6
  • 28
  • 60