java - 按位运算 OR on (double) 在 Java 中不可能,在 JavaScript 中可能

标签 java javascript numbers double bitwise-or

这是 Google Chrome Javascript 控制台的输出。
http://i.stack.imgur.com/gefcZ.png

这是 DrJava Java 控制台的输出。
http://i.stack.imgur.com/bQ7hS.png

我的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:

  1. Let number be the result of calling ToNumber on the input argument.
  2. If number is NaN, +0, −0, +∞, or −∞, return +0.
  3. Let posInt be sign(number) * floor(abs(number)).
  4. 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.
  5. 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/

相关文章:

java - 即使使用 dp,布局也不适合屏幕截图

javascript - jQuery 中奇怪的变量作用域

javascript - Web Worker 的用例是什么?

javascript - 质数 JavaScript

java - 如何打印数字的 float 部分的最后一位?

java - ScheduledExecutorService - 程序在一次性操作后未结束

java - 使用 Spring Rest Template + Spring Web MVC 上传多部分文件(多个文件)

javascript - 如何在 Angular 应用程序中定义模块和配置?

java - 通用十进制格式

javascript - 为输入类型编号添加千位逗号分隔符