I am having trouble understanding converting to and from bytes, or bytes in general
byte b = (byte)170;
System.out.println("Byte to int" + (int)b);
why is it that when I cast 170 to a byte then cast that byte to an int I get -86 and what is the proper way to do this?
EDIT: Okay so the answer to my question was really simple (byte ranges from -128 to 127)…
Where I was getting confused is that I really want is binary 10101010 to be in the byte so I figured represent that number in int and put that in the byte. Can someone please tell me how I can get that binary number into a byte?
The binary representation of 170 as a 32-bit integer is
When you cast that to a
byte, it becomes1010 1010. Since all integers in Java are signed, it sees1010 1010as a 2’s complement 8-bit integer. That’s -86.When you convert this byte back to integer using
(int) b, it gets signed extended to:Which is also -86. You want to apply a bit mask to it, so it becomes 170 again.
(int) (0xff & b)will give you 170 back: