问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/8936523/javascript-bitwise-operator-confusion