0
int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234

I was looking at this code and was confused about how they values were stored. The first int is stored as 32 bits (4 bytes). b converts to binary and stores its signed value (8 bits). Does i2 store it as an 8 bit unsigned representation or does it convert it back to 32 bits?

  • An `int` is always 32-bits. It doesn't change size because you assigned it a value from a different type. – Peter Lawrey Nov 23 '13 at 17:59
  • Also, your question title asks about "int to byte", but the last sentence of the description implies that you're asking about the reverse. Is the byte-to-int conversion the part that is actually confusing you? – Dennis Meng Nov 23 '13 at 19:49

3 Answers3

1

Java does not have unsigned primitive types. All byte variables are signed 8-bit values.

Whether or not the most significant bit is interpreted as a sign bit, when you do bit-wise operations all the bits that are present are used by the operator. To make this concrete, the following are equivalent:

i2 = b & 0xFF;
i2 = b & ((byte) -1);
scottb
  • 9,908
  • 3
  • 40
  • 56
  • *Java does not have unsigned primitive types* -- not true, there is `char`. – arshajii Nov 23 '13 at 15:45
  • @arshajii: Perhaps *"not quite true"*. Although `char` is freely convertible with `int`, I would argue that the sense of `char` is *not* that of a numeric type. – scottb Nov 23 '13 at 16:48
0

i2 is declares as an int, so it should be a full 32-bit value. It will contain the binary AND of b, which in this case is the lower 8 bits and 0xFF.

Brandon
  • 9,822
  • 3
  • 27
  • 37
0

Things aren't "stored as" an unsigned or signed representation. This is a nitpicky distinction, but it seems to be where you're getting confused. The only difference is how the bits are interpreted. What's happening here is the following:

  • i stores the value 11101010 (plus some number of higher order bytes). Under Java's convention for integer storage format, this represents the value 234.
  • b stores the value 11101010, since ints are converted to bytes by simply truncating them. Under Java's convention for numerical byte storage format, this represents the value -22.
  • i2 stores the value 11101010 (plus some number of higher order bytes), because a bitwise operation was applied to b so its bits were directly copied. (Had you written int i2 = b or int i2 = b + 0, the byte would have been converted to its numerical value -22, and then stored as the int representation of -22.
Jose Torres
  • 347
  • 1
  • 3