能有人解释一下这种情况下变量字节的输出，它出现为负数。

go评论70阅读模式

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

}
``````

I know it is out of range for byte

``````public class TypeMismatchVariable {

byte b = (byte) 129;

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

}
``````

In this case I'm having -127 as my output
But I don't have any reason for it

答案1

Byte范围从最小值-128到最大值127（包括在内）。

``````-128（十进制） => 10000000（位）
-127（十进制） => 10000001（位）
...
-1   （十进制） => 11111111（位）
0    （十进制） => 00000000（位）
+1   （十进制） => 00000001（位）
+127 （十进制） => 01111111（位）
``````

``````+129（十进制） => 00000000 00000000 00000000 10000001  （int表示方式）
``````

Byte range is from minimum value of -128 and a maximum value of 127 (inclusive).
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.

For byte type, you only have 8 bits to store the value. You can have only 256 distinct values (2^8 = 256). Java represents negative values with '1' as the highest bit:

``````-128 (dec) =&gt; 10000000 (bit)
-127 (dec) =&gt; 10000001 (bit)
...
-1   (dec) =&gt; 11111111 (bit)
0    (dec) =&gt; 00000000 (bit)
+1   (dec) =&gt; 00000001 (bit)
+127 (dec) =&gt; 01111111 (bin)
``````

When you try to set a value that needs more than one byte to store then setting the lowest byte to a byte value happens:

``````+129 (dec) =&gt; 00000000 00000000 00000000 10000001  (int representation)
``````

but 10000001 (bit) is -127 (dec) in byte representation of java type (as described above)
To have a better understanding of the overflow problem in Java, see the article: https://medium.com/@jeanvillete/java-numeric-overflow-underflow-d6b206f96d88

• 本文由 发表于 2020年7月21日 22:31:45
• 转载请务必保留本文链接：https://go.coder-hub.com/63016836.html
• byte
• java
• type-mismatch
• variables

go 34

go 50

go 62

go 44