Java - 从 Int 到 Short 的显式转换 [英] Java - Explicit Conversion from Int to Short

查看:21
本文介绍了Java - 从 Int 到 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(a缩小原语转换,JLS 5.1.3).这个操作实际上是:100 万模 2^16(short 中的 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屋!

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