Byte A = (byte) 234; system. Out. println ();
The aboveCodeThe result is-22 because byte in Java is signed and the byte range is-128 ~ 127.
If you want to output 234, what should you do? First of all, assign a to a larger type, as shown below:
Byte A = (byte) 234; system. Out. println (a); int I = A; system. Out. println ();
After execution, it is still-22. Because Int Is also signed, when a is assigned to I, the sign bit of a becomes the sign bit of I in I.
The correct method should be:
Byte A = (byte) 234; system. out. println (a); int I = A; system. out. println (a); I = A & 0xff; system. out. println (I );
The reason is:
0xff is int, which occupies 4 bytes and A is byte, which occupies 1 byte. The operation details are as follows:
00000000 00000000 00000000 11101010 ()
&
00000000 00000000 11111111 11111111 (I)
---------------------------------------------------------------------
= 00000000 00000000 00000000 11101010
The result is an int, But the sign bit is 0, indicating a positive number, and finally a positive integer of 234.
In fact, this method can also obtain the unsigned value of the signed Char in the C language, but in the C language, you can directly use unsigned for conversion, which is more convenient than this.