转换具有长整型变量的Java函数为NodeJS。

huangapple go评论67阅读模式
英文:

Convert java function with long variable to NodeJS

问题

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

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?

答案1

得分: 0

如果您阅读了这个答案:https://stackoverflow.com/a/4355475/1725871,Java会将超过Integer.MAX_VALUE的部分对long进行包装,从而该值将变为负数。

显然在Node.js中情况并非如此。

由于longint大,您试图复现的行为实际上是Java实现的副作用,即不安全,即不检查long值是否小于Integer.MAX_VALUE

就个人而言,我不会在我的程序中依赖这样的机制。

英文:

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

答案2

得分: 0

我们可以将数字转换为32位有符号整数,使用内置的Int32Array,如下所示:

function LongToIntExample1(num) {
     return (new Int32Array([num]))[0];
}
 
console.log(LongToIntExample1(2672558412))
console.log(LongToIntExample1(2147483647))
英文:

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

<!-- begin snippet: js hide: false console: true babel: null -->
<!-- language: lang-js -->

function LongToIntExample1(num) {
     return (new Int32Array([num]))[0];
}
 
console.log(LongToIntExample1(2672558412))
console.log(LongToIntExample1(2147483647))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年10月8日 15:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64257800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定