JavaScript Bitwise Masking

前端 未结 2 634
孤独总比滥情好
孤独总比滥情好 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条回答
  • 2021-01-19 06:40

    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.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题