从Ruby获得相同的结果作为Javascript逐位异或 [英] Getting the same result from Ruby as Javascript for bitwise XOR

查看:258
本文介绍了从Ruby获得相同的结果作为Javascript逐位异或的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中:

-1104507 ^ 3965973030 => -3966969949

在Javascript中:

In Javascript:

-1104507 ^ 3965973030 => 327997347



有人问一个的

Someone asked a similar question here but the answer just pointed to a wrapper for Closure. I need a way to get the same answers from Ruby as I get for JavaScript so I can port this code over.

我需要一种能够获得JavaScript来自任何整数的 A ^ B 结果 A B

I need a way of being able to get the JavaScript result from any A ^ B in Ruby for any integers A and B.

推荐答案

这两个的的相同的结果,模2 32 。在Ruby,你可以& 4294967295 来使结果相同,在Javascript。

Those two are the same result, modulo 232. In Ruby you could & 4294967295 to make the result the same as in Javascript.

要覆盖所有的情况下,你需要考虑到的Javascript认为二进制值要签名 32位整数。另一方面,Ruby会从& amp; 生成无符号 32位整数。 。4294967295 操作

To cover all the cases, you need to take into account that Javascript considers binary values to be signed 32-bit integers. Ruby on the other hand will produce unsigned 32-bit integers from the & 4294967295 operation.

所以,在Javascript简单:

So, in Javascript simply:

c = a ^ b

要在Ruby中得到同样的效果:

To get the same thing in Ruby:

c = (a ^ b) & 4294967295
c -= 4294967296 if c > 2147483647

这篇关于从Ruby获得相同的结果作为Javascript逐位异或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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