Training Java – part 6 – how work operators: & , | and ^ ?

This section Training Java shows you how work operators: &, | .

As in last post about bit operators, write example:

public class Test {
public static void main(String[] ar )
{	
 int a = 0b1001;
 int b = 0b1010;
 int c = -2;
 
System.out.print(" a = ");  System.out.print(a);   
System.out.print(",a binary = ");  
System.out.println(Integer.toBinaryString(a));
System.out.print("b = ");  System.out.print(b);   
System.out.print(",b binary = ");  
System.out.println(Integer.toBinaryString(b));
System.out.print("c = ");  System.out.print(c);   
System.out.print(",c binary = ");  
System.out.println(Integer.toBinaryString(c));
    System.out.println(); 

System.out.print("a & b = ");  System.out.print(a & b);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(a & b));
System.out.print("a | b = ");  System.out.print(a | b);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(a | b));
System.out.print("a ^ b = ");  System.out.print(a ^ b);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(a ^ b));
     System.out.println();  
     
System.out.print("a & c = ");  System.out.print(a & c);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(a & c));
System.out.print("a | c = ");  System.out.print(a | c);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(a | c));
System.out.print("a ^ c = ");  System.out.print(a ^ c);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(a ^ c));
     System.out.println();  

System.out.print("b & c = ");  System.out.print(b & c);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(b & c));
System.out.print("b | c = ");  System.out.print(b | c);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(b | c));
System.out.print("b ^ c = ");  System.out.print(b ^ c);
System.out.print(", binary = ");  
System.out.println(Integer.toBinaryString(b ^ c));
     System.out.println();
}
}

Result:

The & sign represents and bit operator.
The | sign represents inclusive or  bit operator.
The ^ sign represents exclusive or  bit operator.

The inclusive or bit operator for 0 and 1 gives 1, for 1 and 1 gives 1 either.
But the exclusive or bit operator for 0 and 1 gives 1, for 1 and 1 gives 0.

These operators compares one bit from first number with bit in the same place in second number and so on.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.