Javascript function rewritten in Java gives different results

In Java, 0x80000000 is outside the range of a 32bit int, so it wraps around to -2147483648.

In JavaScript, 0x80000000 is well inside the range of a 64bit double, so it remains 2147483648.

Obviously, adding -2147483648 vs adding 2147483648 results in a very large discrepancy.

You can either use a long 0x80000000L in Java, or coerce your JS number into a 32bit int with (0x80000000|0), depending on which you want.


Try this. You need to specify long values in doing the conversion.

    public static long normalizeHash(long encondindRound2) {
        if (encondindRound2 < 0) {
            encondindRound2 =  (encondindRound2 & 0x7fffffffL) + 0x80000000L;
        }

        return  (encondindRound2 % 1_000_000);
    }

But there is another issue you should be aware of. Javascript treats % as a modulo operator where Java treats it as a simple remainder operator. Check out this post here for more information.