gpt4 book ai didi

java - 如何将js中的var转成java?

转载 作者:行者123 更新时间:2023-11-29 18:09:10 25 4
gpt4 key购买 nike

现在我尝试将一些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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com