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

huangapple go评论114阅读模式
英文:

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
但我没有任何原因来解释它。

英文:

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

得分: 0

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

有关byte类型,您只有8个位来存储该值。您只能有256个不同的值(2^8 = 256)。Java使用'1'作为最高位来表示负值:

-128(十进制) => 10000000(位)
-127(十进制) => 10000001(位)
...
-1   (十进制) => 11111111(位)
0    (十进制) => 00000000(位)
+1   (十进制) => 00000001(位)
+127 (十进制) => 01111111(位)

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

+129(十进制) => 00000000 00000000 00000000 10000001  (int表示方式)

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

英文:

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) => 10000000 (bit)
-127 (dec) => 10000001 (bit)
... 
-1   (dec) => 11111111 (bit)
0    (dec) => 00000000 (bit)
+1   (dec) => 00000001 (bit)
+127 (dec) => 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) => 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

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定