java类型转换 float类型转换_Java类型转换 – float(和long)到int

2147483648.0实际上是231,而int的最大值是231-1.那么这个浮点值就是一个值太高的值.

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.

这里的相关部分是值将向零.只要浮点值(或长)高于Integer.MAX_VALUE,则转换为int将导致其最高值.对于低于Integer.MIN_VALUE的值也是如此.

如果你使用(int)-214783649L;它会突然变成214783647!为什么这种情况也在JLS中解释,重点是我的:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

该值在二进制中的长时间表示,表示32位截止值,如下所示:

1111 1111 1111 1111 1111 1111 1111 1111 | 0111 1111 1111 1111 1111 1111 1111 1111

当转换发生时,前32位被丢弃,留下最高可能的int.

反向是正的长 – 高32位包含所有1在转换时被丢弃.

完整结构如下,管道再次表示32位标记:

1111 1111 1111 1111 1111 1111 1111 1111 | 1000 0000 0000 0000 0000 0000 0000 0000

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值