2016-08-26 92 views
0

虽然经历了这个理论,但我遇到了这个我不明白的问题。 “如果整数值大于字节范围,则它将以模数(除以整数除以该字节的其余部分)字节范围降低。”在Java中铸造不兼容类型

这个说法是什么意思?我知道整数的范围远远大于字节的范围。 有人可以解释吗? PS:我是编程初学者。 谢谢

+0

复制? http://stackoverflow.com/questions/31674821/conversion-of-integer-to-byte-in-java – muymoo

回答

0

modulo(%)指清洁分割后的剩余部分。如5 % 2 == 1

因此,如果你想创建一个byteint的,它比byte的最大范围更大,它会通过byte最大值分给你,其余为byte的价值。

实施例:

int a = 300 //The max value of a Byte is 256 

byte b = (byte)a; //cast it to a byte, so take the remainder of 300/256. 

//This produces 300 % 256, which is equal to 34. 
+0

如此有效34现在将被存储在'b'中? –

+0

@AnkitSahay这是正确的! – Orin

+0

但这不是显然无效吗?不仅“a”的信息正在丢失,而且由于至少256更接近300,因此存储256而不是34会更有意义吗? 我的意思是为什么即使允许这种类型的转换,编译器的设计是不是应该在超出范围时报告错误? –

0

没有模实际。 Java中的缩小转换会切割位(字节为8位值,整数为32位)。所以我做了字节转换的例子:

int[] values = new int[]{ 300, 128, -1, -129, -4097}; 

for(int i : values) { 
    String intValue = Integer.toString(i); 
    String intBinary = Integer.toBinaryString(i); 
    String byteValue = Byte.toString((byte) i); 
    String byteBinary = intBinary.substring(intBinary.length() - 8); 

    System.out.println("=============="); 
    System.out.println("Int val: " + intValue); 
    System.out.println("Int bin: " + intBinary); 
    System.out.println("Byte val: " + byteValue); 
    System.out.println("Byte bin: " + byteBinary); 
} 

输出是如果你想想模非常意外(128是我的最爱)。请记住,第一位决定数字是正数还是负数,但它也是数值的一部分(这就是为什么字节范围是127到-128)。

============== 
Int val: 300 
Int bin: 100101100 
Byte val: 44 
Byte bin: 00101100 
============== 
Int val: 128 
Int bin: 10000000 
Byte val: -128 
Byte bin: 10000000 
============== 
Int val: -1 
Int bin: 11111111111111111111111111111111 
Byte val: -1 
Byte bin: 11111111 
============== 
Int val: -129 
Int bin: 11111111111111111111111101111111 
Byte val: 127 
Byte bin: 01111111 
============== 
Int val: -4097 
Int bin: 11111111111111111110111111111111 
Byte val: -1 
Byte bin: 11111111 

模的事情是正确的,如果我们在对值进行操作或等于256