byte a = (byte) 234;
System.out.println (a);
The above code, the result is-22, because the byte in Java is signed and the byte range is -128~127.
If you want to output 234, how do you do it, the first thought is to assign a to a larger type, as follows:
byte a = (byte) 234;
int i = A;
System.out.println (a);
After execution, or-22, because INT is also signed, so when a is assigned to I, A's sign bit becomes the sign bit of I in I.
The correct approach should be:
byte a = (byte) 234;
int i = A;
i = a&0xff;
System.out.println (i);
The reason is:
0xFF is int, 4 bytes, A is byte, occupies 1 bytes, the details of the & operation are as follows:
00000000 00000000 00000000 11101010 (a)
&
00000000 00000000 00000000 11111111 (i)
---------------------------------------------------------------------= 00000000 00000000 00000000 11101010
The result is int, but the sign bit is 0, indicating a positive number, and finally a positive integer of 234.
In fact, this method in C language can also get signed char unsigned value, but the C language can be directly used to convert unsigned can, than this convenience.