Skip to content Skip to sidebar Skip to footer

Getting The Same Result From Ruby As Javascript For Bitwise Xor

In Ruby: -1104507 ^ 3965973030 => -3966969949 In Javascript: -1104507 ^ 3965973030 => 327997347 Someone asked a similar question here but the answer just pointed to a wrapp

Solution 1:

Those two are the same result, modulo 2. 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)&4294967295c-=4294967296ifc>2147483647

Solution 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

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

Post a Comment for "Getting The Same Result From Ruby As Javascript For Bitwise Xor"