java 中大家很好奇 Byte的范围为啥是 -128-127。不是应该是 -127-127麻,还有个特殊的-0
public final class Byte extends Number implements Comparable<Byte> {
/**
* A constant holding the minimum value a {@code byte} can
* have, -2<sup>7</sup>.
*/
public static final byte MIN_VALUE = -128;
/**
* A constant holding the maximum value a {@code byte} can
* have, 2<sup>7</sup>-1.
*/
public static final byte MAX_VALUE = 127;
在计算机中,负数以其正值的补码形式表达。
补码:反码加1称为补码。
也就是说,要得到一个数的补码,先得到反码,然后将反码加上1,所得数称为补码。
-5的计算方法如下:
5: 0000 0101 的反码是: 1111 1010。
那么,-5的补码为:
1111 1010 + 1 = 1111 1011
所以,-5 在计算机中表达为:1111 1011。转换为十六进制:0xFB。
同理: -127
127:0111 1111 的反码是 :1000 000
那么,-127的补码为:
1000 000+1= 1000 0001。 转换为十六进制:0x81。
那么 -128=-127-1=1000 0001-1=1000 0000=-0
同理也能解释为啥Integer的范围是 -2147483648-2147483647
public final class Integer extends Number implements Comparable<Integer> {
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;