From the time we touched Java, we were told that the underlying type, byte, is a byte, which occupies 8 bits, and the range represented is -128~127. So why is this range?
?? Let's take a look at the basics of computers:
1. In the computer internal data storage and operation are used binary;
2. The data in the computer is divided into signed number and unsigned number, for the signed number, the computer specifies the highest bit to represent the symbol. "0" indicates positive number, "1" indicates negative number;
3. The data in Java is a signed number;
4. The signed integer in the computer is the complement of the binary.
A concept complement is mentioned here, then the original code and the inverse code must be supplemented.
[Original code]: A computer converts a number to a binary, and at its highest bit with a notation of a representation method.
[anti-code]: According to the provisions, positive number of the anti-code is itself, and negative number of anti-code, in addition to the sign bit, the remaining bits in turn reverse.
[complement]: According to the rules, the positive complement is itself, and the complement of negative, is in its inverse code of the bottom plus 1.
As an example:
Positive 5 and negative 5
5 Original code: 00000101????? -5 Original code: 10000101
? Anti-code: 00000101????? -5 anti-code: 11111010
Complement: 00000101????? -5 Complement: 11111011
?? It is not difficult to think of a byte in Java that can represent the largest binary is 01111111, converted to decimal is 127 (1+2+4+8+16+32+64).
The smallest binary that can be represented is 10000000. But note that this is a complement, we need to follow the rules to find its own original code, first minus 1, get 01111111, and then in reverse, get 10000000, converted to decimal is 128, plus the symbol, namely-128.
?? Finally said a small trick: for the negative complement of the time, can start from the original code low, encountered the first 1 to retain, the back of each bit reversed, of course, the sign bit remains unchanged.
?? Or the above-5 example for the complement, starting from the original code low, the first bit is 1, reserved, and then the back of the bit reversed, the sign bit unchanged, get 11111011.
Why Java byte range is -128~127