Java int operation in Javascript -


java , javascript produces different result when operating large integers.

example: getcode(1747,1763,-268087281,348400) returns 1921968083 in java javascript returns 2.510115715670451e+22.

how result in java using javascript?

having done research problem seems related signed/unsigned 32/64 bit integer operations. have tried adding |0 , of operations , got 1921618368 closer not identical.

java:

public string getcode(int intval1, int intval2, int intval3, int inta) {     int intval5 = intval2 ^ intval3  ;     intval5 = intval5 + (intval1 | inta )  ;     intval5 = intval5 * (intval1 | intval3  ) ;     intval5 = intval5 * (intval2 ^ inta )  ;     return string.valueof(intval5); } 

javascript:

function getcode(intval1,intval2,intval3,inta)  {     var intval5 = intval2 ^ intval3  ;     intval5 = intval5 + (intval1 | inta )  ;     intval5 = intval5 * (intval1 | intval3  ) ;     intval5 = intval5 * (intval2 ^ inta )  ;     return intval5; } 

the |0 trick works operations in javascript simulate 32-bit ints, not multiplication. because multiplying 2 large ints can result in number big exceeds integer precision of javascript's native double type. once cast int, value wrong.

to deal this, math.imul introduced perform true int multiplication. it's new, browser support naturally excludes ie. news though: linked page contains replacement function simulates imul older browsers, works multiplying top , bottom halves of numbers separately.

here how fix function. uses |0 after addition, , math.imul 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 1921968083, identical java.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -