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

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@Johnathan... check out this post... stackoverflow.com/questions/1908492/…
but the second alert gives me a weird number, should I cast it to positive to send it via post?
@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.
thanks, I need to use the 32 flags, will keep it that way as you suggested, ty!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.