I’ve a few lines of code within a project, that I can’t see the value of…
buffer[i] = (currentByte & 0x7F) | (currentByte & 0x80);
It reads the filebuffer from a file, stored as bytes, and then transfers then to buffer[i] as shown, but I can’t understand what the overall purpose is, any ideas?
Thanks
As the other answers already stated,
(currentByte & 0x7F) | (currentByte & 0x80)is equivalent to(currentByte & 0xFF). The JLS3 15.22.1 says this is promoted to anint:because JLS3 5.6.2 says that when
currentBytehas typebyteand0x7Fis anint(and this is the case), then both operands are promoted toint.Therefore,
bufferwill be an array of element typeintor wider.Now, by performing
& 0xFFon anint, we effectively map the originalbyterange -128..127 into the unsigned range 0..255, an operation often used byjava.iostreams for example.You can see this in action in the following code snippet. Note that to understand what is happening here, you have to know that Java stores integral types, except
char, as 2’s complement values.Finally, for a real-world example, check out the Javadoc and implementation of the
readmethod ofjava.io.ByteArrayInputStream: