谁能解释这种情况下可变字节的输出,它以负数出现

Can anyone explain the output of variable byte in this case, it is occuring in negative

我知道它超出字节范围

public class TypeMismatchVariable {

    byte b = (byte) 129;

    public static void main(String[] args) {
        TypeMismatchVariable t1 = new TypeMismatchVariable();
        System.out.println(t1.b);
    }

}

在这种情况下,我将 -127 作为输出 但我没有任何理由

字节范围从最小值 -128 到最大值 127(含)。 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.

对于字节类型,你只有8位来存储值。您只能有 256 个不同的值 (2^8 = 256)。 Java表示以'1'为最高位的负值:

-128 (dec) => 10000000 (bit)
-127 (dec) => 10000001 (bit)
... 
-1   (dec) => 11111111 (bit)
0    (dec) => 00000000 (bit)
+1   (dec) => 00000001 (bit)
+127 (dec) => 01111111 (bin)

当您尝试设置一个需要多个字节存储的值时,将最低字节设置为一个字节值会发生:

+129 (dec) => 00000000 00000000 00000000 10000001  (int representation)

但是 10000001(位)在 java 类型的字节表示中是 -127(十进制)(如上所述) 想要更好的理解Java中的溢出问题,请看文章:https://medium.com/@jeanvillete/java-numeric-overflow-underflow-d6b206f96d88