This question is similar to this other question; however, I\'d like to understand why this is working as it is.
The following code:
console.log((pars
Because bitwise operations (like &
) are done on signed 32-bit integers in javascript. 0xFFFFFFFF
, where all bits are set, is actually -1
, and the 0xde000000
you are expecting is actually -570425344
.
In JavaScript, all bitwise operations (and &
among them) return signed 32-bit integer as a result, in the range −231 through 231−1, inclusive. That's why you have that extra bit (0xde000000
is greater than 0x7ffffff
) representing a sign now, meaning that you get a negative value instead.
One possible fix:
var r = 0xdeadbeef & 0xff000000;
if (r < 0) {
r += (1 << 30) * 4;
}
console.log( r.toString(16) ); // 'de000000'