Search:

Submit Article

Bitwise Operators

Posted By: Reggie Fischer     Category: Java     Views: 82456

Bitwise operators can be used for variables of type char, byte, short, int and long. If we use different type of integers like int and long, the result will be of wider type. Operations on byte and short types may give unexpected results since operands are promoted to integers during intermediate operations.

There are basically three categories of bitwise operators : logical, shift and assignment.

Bitwise Operators

 Operators Meaning ~varName Compliment - Change all zeros to ones and ones to zeros. var1 & var2 And - And each bit of var1 with corresponding bit in var2. var1 | var2 OR - Or each bit of var1 with corresponding bit in var2. var1 ^ var2 XOR - XOR each bit of var1 with corresponding bit in var2. var1 << var2 Shift left - Shift x to the left by y bits. High order bits lost. Zero bits fill in right bits. var1 >> var2 Shift right signed - Shift x to the right by y bits. Low order bits lost. Same bit value as sign (0 for positive numbers, 1 for negative) fills in the left bits. var1 >>> var2 Shift right unsigned - Shift x to the right by y bits. Low order bits lost. Zeros fill in left bits regardless of sign.

Example 1 : Program that displays use of bitwise operators i.e ~, &, |, ^, <<, >>, >>>

class BitwiseOptrDemo
{
public static void main(String args[])
{
int x = 0xAAAA;
int y = 0x9999;
System.out.println("x & y : " + (x & y));
System.out.println("x | y : " + (x | y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("~x : " + (~x));
System.out.println("x << y : " + (x << y));
System.out.println("x >> y : " + (x >> y));
System.out.println("x >>> y : " + (x >>> y));
}
Share:

Didn't find what you were looking for? Find more on Bitwise Operators Or get search suggestion and latest updates.

 Reggie Fischer author of Bitwise Operators is from Frankfurt, Germany. View All Articles