127+1=-128 of byte type in java?

The topic is as follows:

public static void main(String[] args) {
		Byte a = 127;
		System.out.println(++a);
		System.out.println(++a);
		System.out.println(++a);
	}

Output result:

-128
-127
-126

Well, I believe some people feel a little bit embarrassed. I did it at the beginning, and then I thought about it. First, the byte range is -128~127. The byte length is 8 bits, the leftmost is the sign bit, and the binary of 127 is: 0111 1111, so when executing ++a, 0111 111 becomes 1000 0000. As you all know, a computer stores negative numbers in the form of complements. The first bit on the left is the sign bit.

Then the complement of negative numbers in java is converted to decimal as follows:

If a number is positive, its original code, one's complement, and its complement are the same; the complement of a positive number is converted to decimal, which can be converted directly.

Knowing the complement of a negative number, convert it to a decimal number, steps:

      1. Reverse everyone first;

      2. Convert it to a decimal number;

      3. Add the minus sign and subtract 1.

      E.g:

      11111010, the highest digit is 1, which is a negative number. Firstly, you get 00000101 when you invert each bit, and you get 5 when you convert to a decimal number. Add a negative sign to get -5, and then subtract 1 to get -6.

Here is a convincing picture:

It can be seen from the figure that the complement of 127, the original code, and the inverse code are all 0111 1111, then add 1 to become 1000 0000, at this time 1000 0000 (the first digit on the left is 1, negative number, complement) is converted into binary How much is it? You can view it according to the figure, or you can calculate it yourself according to the above method.

1. Invert everyone first, as 0111 1111

2. Convert to binary 127. 

3. Add the minus sign -127 and subtract 1 to -128. So the first output is -128

Looking down, the second output is -127. How did it come from? After adding the computer for the first time, you get 1000 0000, then add 1 to become 1000 0001, and convert it to binary

1. Invert everyone first, as 0111 1110

2. Convert to binary 126

3. Add the minus sign -126 and subtract 1 to -127.

The third output is similar.

Pro test, thank you.

Guess you like

Origin blog.csdn.net/cyberHerman/article/details/89357421