Casting a double to another numeric type

前端 未结 1 1142
一个人的身影
一个人的身影 2021-01-12 15:35

there is something puzzling me and I did not find much information on the VM specs. It\'s a bit obscure and that\'d be nice if someone could explain me.

These few li

相关标签:
1条回答
  • 2021-01-12 15:58

    JLS spells out the rules in section 5.1.3 Narrowing Primitive Conversion. The rules depend on the target type.

    float:

    A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

    int and long:

    one of the following two cases must be true:

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

    byte, char and short:

    If the target type is byte, char or short, the conversion it two-step. First, the double is converted to long as explained above. Then, the long is converted to the final type as follows:

    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.

    0 讨论(0)
提交回复
热议问题