JavaScript按位运算符混淆 [英] Javascript bitwise operator confusion

查看:70
本文介绍了JavaScript按位运算符混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Javascript做一些按位操作,

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

0xff000000 | 0x00aabbcc

我希望给我

0xffaabbcc     // == 4289379276;

但是运行此命令时,我得到的结果是-5588020.我希望这与以下事实有关:JavaScript中的按位运算只能对32位数字进行操作,但是问题中的两个数字< = 32bit还是不行吗?有人可以指出我出了问题的地方以及如何获得期望的结果吗?

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...

全部感谢您的评论.在 JavaScript按位运算符混淆中可以找到答案.事实证明,JavaScript对32位SIGNED整数进行按位运算.我的上面的运算大于最大可能范围,因此结果以带符号的int形式返回.解决方案是将输出右移0,这显然告诉JS再次将其视为无符号.

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

推荐答案

您将获得正确的十六进制值,而不仅仅是您要查找的整数值.

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

4289379276-2 ^ 32 = -5588020

4289379276 - 2^32 = -5588020

我想这是否足够取决于您要如何处理结果.

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

这篇关于JavaScript按位运算符混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆