The |0
trick works well for most operations in JavaScript to simulate 32-bit ints, but not for multiplication. This is because multiplying two large ints can result in a number so big that it exceeds the integer precision of JavaScript's native double
type. Once that is cast back to an int, the value is slightly wrong.
To deal with this, Math.imul
was introduced to perform true int multiplication. It's very new, so browser support naturally excludes IE. Good news though: the linked page contains a replacement function that simulates imul
for older browsers, which works by multiplying the top and bottom halves of the numbers separately.
Here is how to fix your function. It uses |0
after addition, and Math.imul
for multiplication:
function getCode(intVal1, intVal2, intVal3, IntA) {
var intVal5 = intVal2 ^ intVal3;
intVal5 = intVal5 + (intVal1 | IntA) | 0;
intVal5 = Math.imul(intVal5, (intVal1 | intVal3));
intVal5 = Math.imul(intVal5, (intVal2 ^ IntA));
return intVal5;
}
alert(getCode(1747, 1763, -268087281, 348400));
The output is 1921968083
, identical to Java.