Wednesday, October 27, 2010

Bitwise Operators

Java's bitwise operators operate on individual bits of integer (int and long) values. If an operand is shorter than an int, it is promoted to int before doing the operations.

It helps to know how integers are represented in binary. For example the decimal number 3 is represented as 11 in binary and the decimal number 5 is represented as 101 in binary.
Negative integers are store in two's complement form. For example, -4 is 1111 1111 1111 1111 1111 1111 1111 1100.

Bitwise operators can fall under 2 categories.>>,>>>,<< operators are called shift operators, which is covered in this post. Other operators are ~,&,| and ^ operators.
~ Not operator
^ Xor or Exclusive OR
| OR
& And operator
>> Right shift
>>> Unsigned right shift
<< left shift

Note that operands for Bitwise operators must be numeric datatypes(char, short, int, or long).

Examples - The bitwise operators

Operator Usage Example Result Reason
& or and Operator a & b 3 & 5 1 1 if both bits are 1.
| OR operator a | b 3 | 5 7 1 if either bit is 1.
^ or xor operator a ^ b 3 ^ 5 6 1 if both bits are different.
~ or not operator ~a ~3 4 Inverts the bits.
Left shift n << p 3 <<< 2 12 Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
Right shift n >> p 5 >> 2 1 Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
Unsigned right shift n >>> p -4 >>> 28 15 Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

 
 

No comments:

Post a Comment

Chitika