I have this line of code
int b1 = 0xffff & (content[12]<<8 | 0xff & content[11]);
I have a bytearray (content[]) in little endian and need to recreate a 2 byte value. This code does the job just fine but prior to testing i had it written like this
int b1 = 0xffff & (content[12]<<8 | content[11]);
and the result was not right. My question is why is 0xff necessary in this scenario?
A bitwise operator in Java is a symbol/notation that performs a specified operation on standalone bits, taken one at a time. It is used to manipulate individual bits of a binary number and can be used with a variety of integer types – char, int, long, short, byte.
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand.
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
5) What is the name of << bitwise operator in Java? Explanation: Left shift operator shifts individual bits from right side to the left side.
The 0xff
is necessary because of a confluence of two factors:
int
(or long
, if necessary) before acting.The result is that if the high-order bit of content[11]
was set, it will be sign-extended to a negative int
value. You need to then &
this with 0xff
to return it to a (positive) byte value. Otherwise when you |
it with the result of content[12]<<8
, the high-order byte will be all 1s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With