繁体   English   中英

用Java转换不兼容的类型

[英]Casting Incompatible Types in Java

在研究理论时,我碰到了我不明白的那条线。 “如果整数的值大于字节范围,它将以模数(整数除以整数的余数)字节范围为模。

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

模数( % )是指干净划分后的余数。 例如5 % 2 == 1

因此,如果您尝试从int创建一个byte ,并且该byte大于该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.

实际上没有模数。 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的值进行运算,则取模数是准确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM