开发者

problem with bitmask and javascript

开发者 https://www.devze.com 2023-02-27 08:04 出处:网络
I am not sure if I am doing something wrong, but I can\'t seem to have this simple javascript to work:

I am not sure if I am doing something wrong, but I can't seem to have this simple javascript to work:

var a = 0;

a |= (1 << 31);

alert(a);

a |= (1 << 30);

alert(a);

you can see it here htt开发者_StackOverflow中文版p://jsfiddle.net/qPEVk/

shoudln't it 3221225472 ?

thanks,

Joe


There is technically nothing wrong with that, and a negative number is expected because it's casting to a 32bit signed int.

Basically, the leading bit means "negative or positive", so when you flip it (with 1<<31) you get a negative number.

Your bitmask will still work exactly like you expect on up to 32 bits. You can't exceed a 32-bit bitmask in JavaScript.


var a = 0;
var b;
a |= (1 << 31);
b = a
a |= (1 << 30);
b += a
alert(b);

In the above case, b will end up as -3221225472.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号