JavaScript Bitwise Masking

前端 未结 2 659
孤独总比滥情好
孤独总比滥情好 2021-01-19 06:07

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         


        
2条回答
  •  萌比男神i
    2021-01-19 06:47

    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'
    

提交回复
热议问题