现在我尝试将一些js代码转换为java,出现问题:
在js中
46022*65535 = 3016051770
and
(46022*65535)|7867 = -1278910789
在java中
46022*65535 = -1278915526 this is overflow
46022L*65535L = 3016051770L this is the same result to js
(46022*65535)|7867 = -1278910789 this one and the one below is the problem
(46022L*65535L)|7867L = 3016056507L
那么,为什么|
运算符会将两个正数变成负数?
java和js在处理int和long来做这个操作时有什么不同?
那么,在这种情况下,如何编写兼容js的java代码呢?
注意:我知道 int 和 long 的范围,我的问题是 |
。
更多问题:
根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
&
也是32bit操作,则:
在js中
2996101485 & 65535 = 57709
在java中
2996101485 is overflow to int so I use double to store it and cast it into int when I need to do AND.
double a = 2996101485l;
double b = 65535;
int c = (int) a & (int) b; Now c = 65535
但是如果我使用 long 来转换:
long c = (long) a & (long) b; Now c = 57709
所以,仅仅简单地将 double 转换为 int 就会导致问题。我想知道为什么?
我遇到了问题,2996101485 可以在 js 中以 32 位形式出现,而在 java 中它应该很长。所以我编写函数来转换这些操作,例如, &
应该使用这个java函数来运行,在js中给出相同的结果:
private double doOR(double x, double y) {
if (x > Integer.MAX_VALUE && x <= 1l << 32) {
if (y > Integer.MAX_VALUE && y <= 1l << 32) {
return (long) x | (long) y;
} else {
return (long) x | (int) y;
}
} else {
return (int) x | (int) y;
}
}
最佳答案
问题是 JavaScript 中的数字 have roughly 53-bit precision (它们似乎基于浮点 double ),bitwise OR operates on only 32 bits .
Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers.
这意味着在处理算术时,long
将为您提供类似 JavaScript 的算术(带有像您这样的数字),因为 Java int
会溢出;但是当使用按位运算时,int
将为您提供类似于 JavaScript 的结果,因为那时两个平台都在 32 位数字上运行。
关于java - 如何将js中的var转换成java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29000317/