Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bitwise operation

Tags:

java

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?

like image 589
John Avatar asked Apr 04 '13 18:04

John


People also ask

What is bitwise operations in Java?

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.

Is there Bitwise operator in Java?

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.

What is && and || in Java?

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.

What is the name of << Bitwise operator in Java?

5) What is the name of << bitwise operator in Java? Explanation: Left shift operator shifts individual bits from right side to the left side.


1 Answers

The 0xff is necessary because of a confluence of two factors:

  1. All integer types in Java are signed
  2. All bitwise operators promote their arguments to 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.

like image 58
Ted Hopp Avatar answered Sep 19 '22 05:09

Ted Hopp