为什么byte取值-128~127??
轉(zhuǎn)載自?為什么byte取值-128~127??
java設(shè)計(jì)byte類型為1個(gè)字節(jié),1個(gè)字節(jié)占8位,即8bit,這是常識(shí)。
另外,計(jì)算機(jī)系統(tǒng)中是用補(bǔ)碼來存儲(chǔ)的,首位為0表示正數(shù),首位為1表示負(fù)數(shù),所以有以下結(jié)論:
最大的補(bǔ)碼用二進(jìn)制表示為:01111111?= 127
最小的補(bǔ)碼用二進(jìn)制表示為:10000000?= -128
關(guān)于補(bǔ)碼、原碼、反碼的計(jì)算原理可以百度。
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個(gè)字節(jié),即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個(gè)字節(jié),即32/8=4。
其他Short、Long的設(shè)計(jì)原理也一樣。
總結(jié)
以上是生活随笔為你收集整理的为什么byte取值-128~127??的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为s10配置参数?
- 下一篇: 厉害了,Servlet3的异步处理机制