- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是 Google Chrome Javascript 控制台的输出。
这是 DrJava Java 控制台的输出。
我的Javascript代码是
(baseCPUCyclesPerIteration - CPUCyclesTotalRoundoff) | 0
如果两个变量都是整数,似乎在 Java 中编译得很好,但显然它们在 javascript 中是 double 的。尽管
typeof baseCPUCyclesPerIteration
显示 “number”
结果很明显它是 double 据类型。我不明白为什么按位 OR 0
适用于 Javascript 中的 double 但不适用于 Java double 。
似乎是 的目的| 0
只是 trim double 据类型中的小数点。我猜在 Java 中等效的是 (int)
或 (long)
cast 这是正确的吗?或按位 | 0
做的比 javascript 中的小数点更多吗?
编辑:ya | 0
不只是在 javascript 中 trim 只是运行这个。 8899811111.111113453456754645 | 0
返回 309876519
。
(虽然我通过了双重限制大声笑仍然尝试在 javascript 中计算它,我猜这是溢出发生的地方)。
最佳答案
在 javascript 中,所有按位运算符都会将十进制数转换为 32 位整数。它的作用类似于正数的 floor
和负数的 ceil
。 |0
或 ~~
之类的东西在 JavaScript 中经常用作将数字转换为整数的技巧。
为了解释您看到的溢出,我们可以查看有关 Javascript 如何将数字转换为 int32 的规范:http://es5.github.io/#x9.5
The abstract operation ToInt32 converts its argument to one of 2^32 integer values in the range −2^31 through 2^31−1, inclusive. This abstract operation functions as follows:
- Let number be the result of calling ToNumber on the input argument.
- If number is NaN, +0, −0, +∞, or −∞, return +0.
- Let posInt be sign(number) * floor(abs(number)).
- Let int32bit be posInt modulo 2^32; that is, a finite integer value k of Number type with positive sign and less than 2^32 in magnitude such that the mathematical difference of posInt and k is mathematically an integer multiple of 2^32.
- If int32bit is greater than or equal to 2^31, return int32bit − 2^32, otherwise return int32bit.
因此,要重现此行为,您必须重现此逻辑。
编辑:这是 Mozilla 的 Rhino 引擎如何在 Java 中执行此操作:(根据 user3435580 提供的 github 链接)
public static int toInt32(double d) {
int id = (int)d;
if (id == d) {
// This covers -0.0 as well
return id;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
double two32 = 4294967296.0;
d = Math.IEEEremainder(d, two32);
// (double)(long)d == d should hold here
long l = (long)d;
// returning (int)d does not work as d can be outside int range
// but the result must always be 32 lower bits of l
return (int)l;
}
关于java - 按位运算 OR on (double) 在 Java 中不可能,在 JavaScript 中可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22585743/
我是一名优秀的程序员,十分优秀!