Except char
, every other numerical data type in Java are signed.
As said in a previous answer, you can get the unsigned value by performing an and
operation with 0xFF
. In this answer, I'm going to explain how it happens.
int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
// This is like casting b to int and perform and operation with 0xFF
System.out.println(i2); // 234
If your machine is 32-bit, then the int
data type needs 32-bits to store values. byte
needs only 8-bits.
The int
variable i
is represented in the memory as follows (as a 32-bit integer).
0{24}11101010
Then the byte
variable b
is represented as:
11101010
As byte
s are unsigned, this value represent -22
. (Search for 2's complement to learn more on how to represent negative integers in memory)
Then if you cast is to int
it will still be -22
because casting preserves the sign of a number.
1{24}11101010
The the casted 32-bit
value of b
perform and
operation with 0xFF
.
1{24}11101010 & 0{24}11111111
=0{24}11101010
Then you get 234
as the answer.