Java - 从Int到Short的显式转换 [英] Java - Explicit Conversion from Int to Short
本文介绍了Java - 从Int到Short的显式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以解释为什么会出现以下声明:
Can someone please explain why this following statement:
short value = (short) 100000000;
System.out.println(value);
给我:
16960
知道Java中的short的最大值是32767是否正确?
Knowing that the maximum value of a short in Java is 32767 correct?
推荐答案
您的值为1亿,我得到-7936。
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,并且当转换到 short
(a 缩小原始转换,JLS 5.1.3 )。有效地,这个操作:1百万模2 ^ 16(在短
中的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屋!
查看全文