0

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.

Community
  • 1
  • 1
Ben G
  • 26,091
  • 34
  • 103
  • 170

2 Answers2

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
Mark Adler
  • 101,978
  • 13
  • 118
  • 158
  • what about `332763 ^ 2714866558`. This one gives `2715058341` in ruby and `-1579908955` in JS. And if you do `2715058341 & 4294967295` it's still `4294967295` – Ben G Jun 12 '13 at 19:03
  • 1
    You mean it's still 2715058341. See my answer. – Mark Adler Jun 12 '13 at 20:53
0

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
Ben G
  • 26,091
  • 34
  • 103
  • 170
  • You only need one `if`. See my answer. – Mark Adler Jun 12 '13 at 20:54
  • well, yours has `&` and `-`. Mine uses `+` and `-`. Same number of operators, no? – Ben G Jun 12 '13 at 22:09
  • 1
    `if` statements slow things down since they mess with the look-forward execution units. Even if you had more operators, but fewer `if`'s, that would be a win. So one less `if` and the same number of operators is definitely a win. I should see if I can get rid of the remaining `if` with more operators. – Mark Adler Jun 12 '13 at 23:11
  • Not that that really matters much, since ruby is an interpreter. – Mark Adler Jun 12 '13 at 23:14