Bitwise and shift operators



These operators are low-level operators that are used on integer and long values. They are used to either test for bits or change the value of certain bits in a number.
The bitwise and shift operators can only be used with integer numbers, not floating-point numbers. Bitwise operators can be used with booleans and then they evaluate both expressions regardless of the value of the first one.

If either of the arguments to a bitwise operator is a long, the result is a long. Otherwise, the result is an int. If the left operand of a shift operator is a long, the result is a long – otherwise, the result is an int.


Bitwise complement (~)

This operator inverts ones and zeros in a number.
For example, convert a number to negative and back:

Gives the output:


Bitwise AND (&)

This operator combines its two integer operands by performing a boolean AND operation on their individual bits.
The result has a bit set only if the corresponding bit is set in both operands:

When used with boolean operands, & acts like && but evaluates both operands regardless of the outcome of the first operand.


Bitwise OR (|)

This operator combines its two integer operands by performing a boolean OR operation on their individual bits.
The result has a bit set if the corresponding bit is set in either or both of the operands:

When used with boolean operands, | acts like || but evaluates both operands regardless of the outcome of the first operand.


Bitwise XOR (^)

The XOR operator combines two integers by checking if a certain bit has a different value in the other number.
In that case the bit in the combined number evaluates to 1. If both bits have the value of 0 or if they both have the value of 1, then the new bit gets the value 0:


Left shift (<<)

The Left shift operator shift bits to the left in the left operand as many times as the right operand specifies.
High order bits disappear and zeros are added as low order bits (from the right).


Signed right shift (>>)

Behaves like left shift operand but the opposite way. The bits of the left operand are shifted to the right by as many positions as specified by the right operand.
The low level bits disappear and the bits coming in from the left (high order) have the value of the original high order bit, i.e. if the original number was positive then zeros are shifted in, otherwise ones.
That is why it is called signed.


Unsigned right shift (>>>)

Acts as the Signed right shift operator except that zeros are always shifting in from the left.
Should the original integer be a negative number, then it’ll end up as a positive number after the shifting.







Search for more Java info on this site here:
Custom Search


Please type any questions here.