Getting the same result from Ruby as Javascript for bitwise XOR

微笑、不失礼 提交于 2020-01-17 08:34:13

问题


In Ruby:

-1104507 ^ 3965973030 => -3966969949

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.

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


回答1:


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

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.

So, in Javascript simply:

c = a ^ b

To get the same thing in Ruby:

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



回答2:


Thanks to Mark Adler for the initial tip, I think this is the way to do it algorithmically:

max_32_int = (2**32)

c = a ^ b

if c > (max_32_int/2)
  c = c - max_32_int
elsif c < -(max_32_int/2)
  c = c + max_32_int
end


来源:https://stackoverflow.com/questions/17056263/getting-the-same-result-from-ruby-as-javascript-for-bitwise-xor

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