为什么byte取值-128~127??
轉載自?為什么byte取值-128~127??
java設計byte類型為1個字節,1個字節占8位,即8bit,這是常識。
另外,計算機系統中是用補碼來存儲的,首位為0表示正數,首位為1表示負數,所以有以下結論:
最大的補碼用二進制表示為:01111111?= 127
最小的補碼用二進制表示為:10000000?= -128
關于補碼、原碼、反碼的計算原理可以百度。
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;
7是最高位,總共8bit,可以看出byte占1個字節,即8/8=1。
Integer源碼:
/**
?* A constant holding the minimum value an {@code int} can
?* have, -2<sup>31</sup>.
?*/
public static final int ? MIN_VALUE = 0x80000000;
/**
?* A constant holding the maximum value an {@code int} can
?* have, 2<sup>31</sup>-1.
?*/
public static final int ? MAX_VALUE = 0x7fffffff;
31是最高位,總共32bit,可以看出int占4個字節,即32/8=4。
其他Short、Long的設計原理也一樣。
總結
以上是生活随笔為你收集整理的为什么byte取值-128~127??的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为s10配置参数?
- 下一篇: 厉害了,Servlet3的异步处理机制