In Java, the byte type is signed, and Java does not provide the unsigned byte type. Therefore, its representation range is between-128-127. In this way, for some I/O processingProgramIt is necessary to consider the symbol bit problem. The common practice may be:
Int unsignedbyte = signedbyte> = 0? Signedbyte: signedbyte + 256;
Here we find that because of the byte symbol bit relationship, we have to use the int type with a longer length to deal with the problem caused by the symbol bit. Therefore, we will think that the byte has a smaller range because of the consideration of the symbol bit, so we have to use int for processing. During the conversion of this type, the int type of any length truncates its high bytes to adapt to the byte type, because the int type is wider than the byte type. That is why 127 of an int is converted to byte or 127.
However, when an int value is greater than the value range indicated by a byte value, the problem arises. For example, if the int 128 is converted to a byte type, the value is-128. This is because of the relationship between the complement operation. First, the hexadecimal value of 128 is 0x00000080. When the int to byte type conversion is performed, the previous 0 is truncated to form 0x80. In binary, 0x80 can be written as 10000000. If this is an unsigned number, all operations are normal, but if it is an unsigned number, it will undergo a complement operation. For a negative number, its complement operation is the inverse code (that is, 1 is converted to 0 and since it is) plus one. Which? The complement code of 10000000 is 01111111 plus one, that is, 10000000 = 128 (decimal ). Therefore, byte0x80 actually represents
It is-128. For a similar int type, 129 is-127 of the byte type, and 130 of the int type is-126 of the byte type until 255 of the int type corresponds to-1 of the byte type.
what if it reaches 256? At this time, the status byte is filled with 0, in short, 256 is 0x00000100. Therefore, converting to byte is 0, and the conversion cycle is 256. Therefore, based on the above principle, the following rule is obtained:
byte bytevalue = 0;
int temp = intvalue % 256;
If (intvalue <0) {
bytevalue = (byte) (temp <-128? 256 + temp: temp);
}< br> else {
bytevalue = (byte) (temp> 127? Temp-256: temp);
}< br> during the above process, we can convert signed bytes into unsigned bytes (stored in int type ), you can also convert signed data that exceeds the byte range into signed bytes.