Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Regarding the type conversion operation in java, why does an int type 128 become-128 when it is converted into a byte type?
Regarding the type conversion operation in java, why does an int type 128 become-128 when it is converted into a byte type?
This involves the knowledge of complement. Let me write a conclusion for you first: the complement of a positive number is its own binary representation, and the complement of a negative number = the complement of a positive number+1 (the complement is the inversion of all bits in the binary system), and it is stipulated that the first bit is the sign bit that does not represent the value, 0 is positive, and 1 is negative.

What's the use of talking so much? Yes! Integers are stored in the form of complement in the computer.

Well, with the foundation, let's look at this problem. Int type 128, no problem, the storage boundary of int is much larger than 128. And converted to byte type, the problem comes. Let's look at the binary representation of the int type 128: 0000-0000-0000-1000-0000, which is its complement.

Converted to byte type is expressed as:

1000-0000

We will find that the first place here needs to be represented by a value! But unfortunately, the computer will not automatically identify the expected value when modeling. 1000-0000 is a complement rather than a string of positive binary numbers in a computer. In turn, we get 0 11111,and find that it is the maximum byte type value of 127. Add one to get 128, and the first one is.

This is why the value of byte type is between-128~ 127. The latter method is the same, so I won't go into details.

Of course, the knowledge of complement is not limited to this. If you are interested, you can find relevant information online.