JavaScript Bitwise Masking

北慕城南 提交于 2019-12-01 22:04:44

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'

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!