The bitwise operators &, ^, and | provide bitwise AND, Exclusive-OR
(XOR), and OR operations, respectively
The bitwise operators are applicable to integral types
For AND operations, 1 AND 1 produces 1. Any other combination produces
0
For XOR operations, 1 XOR 0 produces 1 as does 0 XOR 1. The other two
possible combinations produce 0
For OR operations, 0 OR 0 produces 0. Any other combination produces
1
The boolean operators &, ^, and | function for booleans in the same way
that the bitwise operators function for integral types
The Bitwise Operators
The following examples use eight bit values for the sake of brevity.
1001 0110
1100 1100
AND ---------
1000 0100
(Since only the first and sixth column had matching ones, they are the only
columns with a result of one.)
1001 0110
1100 1100
XOR ---------
0101 1010
(If both values in a column are 0 or both are 1, then the result is 0. XOR
is best thought of as one or the other but not both.)
1001 0110
1100 1100
OR ---------
1101 1110
(As long as at least one value in the column is 1 then the result is one.)
The Boolean Operators
These work the same as with the bitwise operators except that you work with
only two values at at time. Consider these examples:
true AND true = true
true AND false = false
false AND false = false
true XOR true = false
true XOR false = true
false XOR false = false
true OR true = true
false OR false = false
Applet Example:
import java.awt.*;
import java.applet.*;
public class bitwise extends Applet{
int x;
int a;
int p, q, r;
public void init(){
setBackground(Color.black);
x=216;
a=111;
p=x & a; //AND
q=x | a; //OR
r=x ^ a; //XOR
}
public void paint(Graphics g){
g.setColor(Color.yellow);
g.drawString(""+x+" & "+a+" = "+p, 20, 20);
g.drawString(""+x+" | "+a+" = "+q, 20, 40);
g.drawString(""+x+" ^ "+a+" = "+r, 20, 60);
}
}
x
Assignment:
One of the constructors used in java.awt.Color takes a single integer as an
argument. It works like this:
int c1 = 0xff0000; //hex value for red
g.setColor(new Color(c1));
g.fillRect(10,10,20,20);
Your job will be to create an applet that is laid out like the snapshot of
the applet shown here. The first column contains three unaltered values (c1,
c2, c3, you set them to three interesting values). The second column
contains the ANDed values (c1 & c2, c2 & c3, and c1 & c3). The third column
contains the ORed values and the fourth column contains the XORed values.
You pick your original colors... but experiment with different values to get
an idea of how AND, XOR, and OR can be used to manipulate color values.