1

I'm trying to do some bitwise operations in Javascript,

0xff000000 | 0x00aabbcc

Which I expect to give me

0xffaabbcc     // == 4289379276;

However when running this, I get the result -5588020. I expect this has something to do with the fact that bitwise operations in javascript only operate on 32 bit numbers, but aren't the two numbers in question <= 32bit anyway? Can someone point out where I'm going wrong and how I can get the desired result?

I've tried the technique outlined at How to do bitwise AND in javascript on variables that are longer than 32 bit? with no luck.


Unable to post my own answer so putting it here for someone else to post...

Thanks for the comments, all. It turns out the answer at Javascript bitwise operator confusion covers this. It turns out that JavaScript does bitwise operations on 32 bit SIGNED ints. My | oepration above was larger than the maximum possible range, therefore the result came back as a signed int. The solution is to shift the output right by 0, which apparently tells JS to treat it as unsigned again.

(0xff000000 | 0x00aabbcc)>>>0
4
  • 1
    What exactly are you expecting? That looks about right for signed integers. Commented Jan 20, 2012 at 3:53
  • I'm expecting the number 4289379276 as a result, but instead I get -5588020. What gives? Commented Jan 20, 2012 at 3:55
  • 2
    That is 0xffaabbcc as a signed integer. Commented Jan 20, 2012 at 3:57
  • 1
    Here is further discussion about this issue: stackoverflow.com/questions/28519708/javascript-bitwise-masking/… Commented Feb 14, 2015 at 20:22

1 Answer 1

2

You are getting the right hex value, it's just not the integer value you're looking for.

4289379276 - 2^32 = -5588020

I suppose whether that suffices as is depends on what you're trying to do with your result.

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

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.