Java - 从 Int 到 Short 的显式转换 [英] Java - Explicit Conversion from Int to Short
问题描述
谁能解释一下为什么会有以下声明:
Can someone please explain why this following statement:
short value = (short) 100000000;
System.out.println(value);
给我:
-7936
知道Java中short的最大值是32767正确吗?
Knowing that the maximum value of a short in Java is 32767 correct?
推荐答案
以你的价值 1 亿,我得到 -7936.把1亿换成100万只能得到16960.
With your value of 100 million, I get -7936. I can only get 16960 if I change 100 million to 1 million.
原因是short
值被限制在-32768到+32767之间,而Java在转换为short
(ashort
中的 16 位)是 16960.
The reason is that short
values are limited to -32768 to +32767, and Java only keeps the least significant 16 bits when casting to a short
(a narrowing primitive conversion, JLS 5.1.3). Effectively this operation: 1 million mod 2^16 (16 bits in a short
) is 16960.
这篇关于Java - 从 Int 到 Short 的显式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!