0

In Java function have "long" variable.

public class LongToIntExample1{  
    public static void main(String args[]){  
        long l=2672558412L;  
        int i=(int)l;  
        System.out.println(i);  
    }
}

=> Output: -1622408884

I tried with NodeJS function as below but wrong output:

module.exports.LongToIntExample1 = () => {
    var l = 2672558412n;
    var i = parseInt(l);
    console.log(i);
}

=> Output: 2672558412

How to write NodeJS function as Java function with same output?

Dang Thach Hai
  • 347
  • 3
  • 10

2 Answers2

0

If you read this answer: https://stackoverflow.com/a/4355475/1725871 Java will wrap the part of the long that is over Integer.MAX_VALUE around and the value will become negative.

Clearly that is not the case in NodeJS

Since a long is bigger than an int, the behaviour you are trying to reproduce is actually a biproduct of the Java implementation not being safe, ie not checking if the long value is less than Integer.MAX_VALUE

Personally I would not rely on a mechanic like that in my programs

JoSSte
  • 2,953
  • 6
  • 34
  • 54
  • `Integer.MAX_VALUE` is the wrong thing to subtract; and this may require billions of subtractions, so it is not a good solution. – kaya3 Oct 08 '20 at 07:59
  • Simply subtracting it would not be correct in most cases where it is bigger than `2x Integer.MAX_VALUE`, as the referred to answer suggests, it's a rollover, and the algorithm would be much more complex. Besides that `Integer.MAX_VALUE` is dependent on architecture and so on, and no matter what, basically the OP is depending on an unsafe conversion function. I would not use this kind of rounding in my programs, as I also stated. – JoSSte Oct 08 '20 at 10:53
  • `Integer.MAX_VALUE` is not platform-dependent; it is defined as 2^31 - 1. The correct thing to subtract would be 2^32, but doing billions of subtractions just to cast from long to int would be extremely inefficient. – kaya3 Oct 08 '20 at 16:40
0

We can cast the number to a 32-bit signed int, using the built-in Int32Array like so:

function LongToIntExample1(num) {
     return (new Int32Array([num]))[0];
}
 
console.log(LongToIntExample1(2672558412))
console.log(LongToIntExample1(2147483647))
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40