With the exception of char , all other numeric data types in Java are signed.
As stated in the previous answer, you can get an unsigned value by doing and operations with 0xFF . In this answer, I am going to explain how this happens.
int i = 234; byte b = (byte) i; System.out.println(b);
If your machine is 32-bit, then 32-bit is required to store int data type values. byte needs only 8 bits.
The variable int i is represented in memory as follows (as a 32-bit integer).
0{24}11101010
Then the byte variable b is represented as:
11101010
Since byte not signed, this value represents -22 . (Find 2 add-ons to learn more about how to represent negative integers in memory)
Then, if you cast is to int it will still be -22 because the cast preserves the sign of the number.
1{24}11101010
The given 32-bit value of b executes and works with 0xFF .
1{24}11101010 & 0{24}11111111 =0{24}11101010
Then you will get 234 as an answer.
Ramesh-X May 09 '19 at 5:20 AM-05-05-09 05:20
source share