gpt4 book ai didi

java - 如何在 Java 中使用 double to int cast

转载 作者:IT老高 更新时间:2023-10-28 20:22:48 25 4
gpt4 key购买 nike

我是 Java 新手,想知道 double to int cast 是如何工作的?我知道通过取低 32 位来 long 到 int 很简单,但是 double(64 位)到 int(32 位)呢?二进制中 double 的那些 64 位是 double 浮点格式(尾数),那么它如何在内部转换为 int 呢?

最佳答案

全部记录在 section 5.1.3 中JLS.

In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:

If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.

  • Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:

    • If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.

    • Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.

  • Otherwise, one of the following two cases must be true:

    • The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.

    • The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

(此处第二步无关,当Tint时。)

在大多数情况下,我希望使用硬件支持实现 - 将 float 转换为整数通常由 CPU 处理。

关于java - 如何在 Java 中使用 double to int cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514958/

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