Java bitwise operation
•
Java
I have this line of code
int b1 = 0xffff & (content[12]<<8 | 0xff & content[11]);
I have a small bytearray (content []), which needs to recreate a 2-byte value This code does the job, but that's how I wrote it before testing
int b1 = 0xffff & (content[12]<<8 | content[11]);
The result is wrong My question is why do I need 0xff in this case?
Solution
Due to the confluence of two factors, 0xff is necessary:
>All integer types in Java are signed > all bitwise operators promote their arguments to int (or long if necessary) before execution
As a result, if the high bit of content [11] is set, it will be extended to a negative int value by the symbol You need & this with 0xff to return it to the (positive) byte value Otherwise, when you are in the result of content [12] < 8, the high-order bytes will all be 1
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码