简体   繁体   English

用Java转换不兼容的类型

[英]Casting Incompatible Types in Java

While going through the theory I came across this line which I don't understand. 在研究理论时,我碰到了我不明白的那条线。 "If integer's value is larger than the range of byte, it will be reduced modulo (the remainder of an integer division by the) bytes range." “如果整数的值大于字节范围,它将以模数(整数除以整数的余数)字节范围为模。

What does this statement mean? 这句话是什么意思? I know that range of integer is much greater than the range of byte. 我知道整数的范围远大于字节的范围。 Can someone explain? 有人可以解释吗? PS : I am a beginner in programming. PS:我是编程的初学者。 Thanks 谢谢

Modulo ( % ) means remainder after clean division. 模数( % )是指干净划分后的余数。 Such as 5 % 2 == 1 例如5 % 2 == 1

Therefore, if you are trying to create a byte out of an int and it is larger than the max range of the byte , it will divide by the max value of byte and give you the remainder as the byte 's value. 因此,如果您尝试从int创建一个byte ,并且该byte大于该byte的最大范围,则它将除以byte的最大值,并为您提供余数作为该byte的值。

Example: 例:

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.

There is no modulo actually. 实际上没有模数。 Narrowing conversion in Java cuts bits (byte is 8 bit value, integer is 32 bit). Java中的缩小转换会削减位(字节是8位值,整数是32位)。 So I made an example of byte conversion: 所以我举了一个字节转换的例子:

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);
}

The output is pretty unexpected if you think about modulo (the 128 is my favourite). 如果考虑模数(128是我的最爱),则输出是非常意外的。 Remember that the first bit decides whether the number is positive or negativ, but it is also a part of value (that is why byte range is 127 to -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

Modulo thing is accurate if we operate on values over or equal 256. 如果我们对大于或等于256的值进行运算,则取模数是准确的。

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

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