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
The result of a bitwise AND operation has a 1 on that bits where both bits are 1 while the result of a bitwise OR operation hase a on that bits where either one of bot bits is 1.
So an example evaluation for the value 0x65:
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
currentByte
has typebyte
and0x7F
is anint
(and this is the case), then both operands are promoted toint
.Therefore,
buffer
will be an array of element typeint
or wider.Now, by performing
& 0xFF
on anint
, we effectively map the originalbyte
range -128..127 into the unsigned range 0..255, an operation often used byjava.io
streams 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
read
method ofjava.io.ByteArrayInputStream
:The good thing about these kinds of logical operations: you can try every possible combination (all 256 of them) and verify that you get the answer you expected.
is equivalent to
which equals
which is exactly the same as
Edit: I only looked at the right side of the assignment, and I still think the equivalance is true.
However, it seems like the code wants to cast the signed byte to a larger type while interpreting the byte as unsigned.
Is there an easier way to cast signed-byte to unsigned in java?
Turns out, the file which the byte was being read from was in a signed bit notation, and of a different length, therefore it was requried to perform this task to allow it to be extended to the java int type, while retaining its correct sign :)
The complicated bitwise logic is completely superfluous.
does the same thing. If buffer is declared as an array of bytes you may even leave out the & 0xff, but unfortunately the declaration is not shown.
The reason may be that the original developer was confused by bytes being signed in Java.