请检查以下内容..
short t = (short)23252525;
System.out.println(t);上面会将输出打印为"-12755“我知道'23252525‘太大了,不适合短,因此溢出,有时显示负数。(- 32,768至32,767)
但现在请看一下这个。
int j = 65536;
for (int i=0;i<10;i++)
System.out.println((short)(i*j));为什么上面总是打印0?
谢谢,
Sanone
发布于 2015-02-22 21:03:59
65536是0000000000000001 0000000000000000。将其强制转换为short会留下底部16位,所有这些位都是0。当您将65536乘以正整数时,您得到的更大的整数的底部16位仍然全为0。
0*j 00000000000000000 0000000000000000
1*j 00000000000000001 0000000000000000
2*j 00000000000000010 0000000000000000
3*j 00000000000000011 0000000000000000
4*j 00000000000000100 0000000000000000
5*j 00000000000000101 0000000000000000
6*j 00000000000000110 0000000000000000
7*j 00000000000000111 0000000000000000
8*j 00000000000001000 0000000000000000
9*j 00000000000001001 0000000000000000因此,当转换为short时,i*j仍然为0。
发布于 2015-02-22 20:59:18
因为它是65536的倍数,溢出到0。
所以正如你所指出的,短的范围是-32,768到32,767,
so when you have short as 32768, it overflows and goes to –32768,
if your short goes to 32769, it will print -32767. 类似地,如果你的空头到了65536,它又回到了0,因此你看到的是0。
https://stackoverflow.com/questions/28658042
复制相似问题