问题描述
当我执行这段代码时,它给出的 s 值为 -7616.为什么这样?这是因为将数据从 int 转换为 short 时丢失数据还是其他原因?
When i execute this code it gives value of s as -7616.Why so? Is this because loss of data while converting it to short from int or something else?
public static void main(String[] args) {
// TODO code application logic here
short s=0;
int x=123456;
int i=8;
s +=x;
System.out.println(s);
}
推荐答案
好问题!这让我想到了很久没有想过的事情,我不得不复习一些概念.谢谢你帮我把我脑子里的锈去掉.
Good question! It made me think about things I haven't thought about in a long while and I had to brush up on a couple of concepts. Thanks for helping me knock the rust off my brain.
对我来说,这类问题最好以二进制形式呈现(原因很快就会变得显而易见):
For me this type of question is best visualized in binary (for reasons that will quickly become apparent):
您的原始号码(请原谅前面的零;我喜欢 4 人一组):
Your original number (forgive the leading zeroes; I like groups of 4):
0001 1110 0010 0100 0000
然而,根据 Java 语言规范 (JLS),short 是一个 16 位有符号二进制补码整数 第 4.2 节.将整数值 123456 分配给 short 称为缩小原语转换",在 JLS 5.1.3.具体来说,有符号整数到整数类型 T 的缩小转换只会丢弃除 n 个最低位之外的所有位,其中 n 是用于表示类型 T 的位数."
A short, however, is a 16-bit signed two's complement integer according to the Java Language Specification (JLS) section 4.2. Assigning the integer value 123456 to a short is known as a "narrowing primitive conversion" which is covered in JLS 5.1.3. Specifically, 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."
丢弃除最低 16 位之外的所有内容给我们留下:
Discarding all but the lowest 16 bits leaves us with:
1110 0010 0100 0000
在无符号整数中,此值为 57,290,但短整数是有符号二进制补码整数.最左边的 1 表示负数;要获得数字的值,您必须反转位并加 1:
In an unsigned integer this value is 57,290, however the short integer is a signed two's complement integer. The 1 in the leftmost digit indicates a negative number; to get the value of the number you must invert the bits and add 1:
原文:
1110 0010 0100 0000
反转位:
0001 1101 1011 1111
加1:
0001 1101 1100 0000
将其转换为十进制并加上负号得到 -7,616.
Convert that to decimal and add the negative sign to get -7,616.
再次感谢您的提问.不知道一些事情是可以的,所以继续提问和学习.我回答得很开心……我喜欢潜入 JLS,疯了,我知道!
Thanks again for asking the question. It's okay to not know something so keep asking and learning. I had fun answering...I like diving into the JLS, crazy, I know!
这篇关于奇怪的结果增加空头超过其最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!