英文:
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中情况并非如此。
由于long
比int
大,您试图复现的行为实际上是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 -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论