# Programming Tutorials

## Using the Bitwise Logical Operators

By: aathishankaran Printer Friendly Format

Using the Bitwise Logical Operators

The following program demonstrates the Bitwise logical operators:

//Demonstrate the Bitwise logical operators

class BitLogic {

public static void main (String args[]) {

String binary[] = {

â€œ0000â€, â€œ0001â€, â€œ0010â€, â€œ0011â€, â€œ0100â€, â€œ0101â€, â€œ0110â€, â€œ0111â€,

â€œ1000â€, â€œ1001â€, â€œ1010â€, â€œ1011â€, â€œ1100â€, â€œ1101â€, â€œ1110â€, â€œ1111â€

};

int a = 3; // 0 + 2 + 1 or 0011 in binary

int b = 6; // 4 + 2 + 0 or 0011 in binary

int c = a | b;

int d = a & b;

int e = a ^ b;

int f  = ( ~a & b) | ( a & ~b);

int g = ~a & 0x0f;

System.out.println(â€œ          a = â€œ + binary[a]);

System.out.println(â€œ          b = â€œ + binary[b]);

System.out.println(â€œ             a | b = â€œ + binary[a]);

System.out.println(â€œ           a & b = â€œ + binary[a]);

System.out.println(â€œ            a ^ b = â€œ + binary[a]);

System.out.println(â€œ~a&b | a&~b = â€œ + binary[a]);

System.out.println(â€œ          ~a = â€œ + binary[a]);

}

}

In this example, a and b has bit patterns, which present all four possibilities for two binary digits: 0-0, 0-1, 1-0, and 1-1. You can see how the | and & operate on each bit by the results in c and d. The values assigned to e and f are the same and illustrate how the ^ works. The string array named binary holds the human-readable, binary representation of the numbers 0 through 15. in this example, the array is indexed to show the binary representation of each result. The array is constructed such that the correct string representation of a binary value n is stored in binary [n]. The value of ~a is ANDed with 0x0f (0000 1111 in binary) in order to reduce its value to less than 16, so it can be printed by use of the binary array. Here is the output from this program.

a = 0011

b = 0011

a | b = 0011

a & b = 0011

a ^ b  = 0011

~a&b | a&~b  = 0011

~a = 0011

 Most Viewed Articles (in Java ) Latest Articles (in Java)

Comment on this tutorial