Javascript bitwise operator confusion

好久不见. 提交于 2019-12-25 02:32:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!