如何在Java中双向int转换工作 [英] How does double to int cast work in Java

查看:131
本文介绍了如何在Java中双向int转换工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,想知道double to int如何工作?我理解,它很简单的长整型通过采取低32位,但双(64位)到int(32位)呢?那么从二进制的double中的那些64位是双精度浮点格式(Mantissa),那么如何在内部转换为int?

解决方案

这些都记录在第5.1.3节


在第一步中,如果T长则将浮点数转换为long,一个int,如果T是byte,short,char或int,如下:




  • 否则,如果浮点数字不是无穷大,浮点值舍入到整数值V,使用IEEE 754向零舍入模式(§4.2.3)向零舍入。然后有两种情况:




    • 如果T是long,并且这个整数值可以表示为long,


    • 否则,如果这个整数值可以表示为int,那么第一步的结果是int value V。



  • 否则,以下两种情况之一必须为真:




    • 该值必须太小(大值或负无穷大的负值),第一步的结果是最小的可表示


    • 值必须太大(大值或正无穷大的正值),而第一步的结果是类型int或long的最大可表示值。




T int 时,第二步是不相关的) p>

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


I am new to Java, and wondering how does double to int cast work ? I understand that it's simple for long to int by taking the low 32 bits, but what about double (64 bits) to int (32 bits) ? those 64 bits from double in binary is in Double-precision floating-point format (Mantissa), so how does it convert to int internally ?

解决方案

It's all documented in section 5.1.3 of the 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:

  • 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.

(The second step here is irrelevant, when T is int.)

In most cases I'd expect this to be implemented using hardware support - converting floating point numbers to integers is something which is usually handled by CPUs.

这篇关于如何在Java中双向int转换工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆