0

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 http://jsfiddle.net/qPEVk/

shoudln't it 3221225472 ?

thanks,
Joe

Jonathan
  • 4,724
  • 7
  • 45
  • 65

2 Answers2

4

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.

  • 1
    @Johnathan... check out this post... http://stackoverflow.com/questions/1908492/unsigned-integer-in-javascript – El Guapo Apr 18 '11 at 16:44
  • but the second alert gives me a weird number, should I cast it to positive to send it via post? – Jonathan Apr 18 '11 at 16:45
  • @Jonathan - No, if you cast it to positive you mess up a lot of things. The 2nd alert is simply `11000000 00000000 00000000 00000000` as a _SIGNED_ int. Your post will understand it properly in just about any language. If you're really concerned about it (or just seems too weird), restrict yourself to 31 bits. –  Apr 18 '11 at 16:46
  • thanks, I need to use the 32 flags, will keep it that way as you suggested, ty! – Jonathan Apr 18 '11 at 16:57
0
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.

Mark Costello
  • 4,334
  • 4
  • 23
  • 26