Sometimes sticking to the signed part of a data type’s range isn’t possible. When we’re
working with unsigned bytes, we can store any number from 0 to 255. However, Java
will normally only let us store numbers in the range of -128 to 127, and 255 is definitely outside of that range. While we can’t write code that says byteb=255;, there is
a way to fool Java into interpreting the number as a signed byte.
Let’s take a look at the binary value for 255: in binary, we would represent this
number as 11111111. We just need to find a way of telling Java to put these bits into
the byte. It turns out that we can do this if we use Java’s bit masking to mask off the
last eight bits of the number 255 as follows:
This works because Java will interpret the number literal of 255 as being a 32-bit
integer, which is big enough to hold the number 255. However, once we’ve assigned
255 to the byte, Java will actually see this byte as -1 instead of as 255, because to
Java this byte is signed, and it will interpret the value using two’s complement.
However, OpenGL or anywhere else expecting unsigned numbers will see the byte as
To read the value back in Java, we can’t just read it directly because Java sees it as
-1. Instead, we need to use a larger Java data type to hold the result. For example,
we could do the conversion with the following code:
We can’t just use shorts=b;because Java will do sign extensionand our short will
still be -1. By telling Java to mask off the last eight bits, we implicitly convert to an
integer, and then Java will correctly interpret the last eight bits of that integer as
255. Our short will then be set to 255, as we expected.