Training Java – part 5 – how work ~ operator?

Binary data work with bitwise operators as ~, & and | . How them work, I describe you in this post.

Begin with ~ operator. Write this code:

public class Test {
public static void main(String[] ar )
{	
 int a = 8;
 int b = 0b1010;
 int c = 0b0000; 
 int d = -1;
 int e = 1;
 
System.out.print("a = ");  System.out.print(a);   
System.out.print(",a binary = ");  
System.out.println(Integer.toBinaryString(a));
System.out.print("~a = ");  System.out.print(~a);
System.out.print(", ~a binary = ");  
System.out.println(Integer.toBinaryString(~a));
     System.out.println(); 
System.out.print("b = ");  System.out.print(b);    
System.out.print(",b binary = ");  
System.out.println(Integer.toBinaryString(b));
System.out.print("~b = ");  System.out.print(~b);
System.out.print(", ~a binary = ");  
System.out.println(Integer.toBinaryString(~b));   
     System.out.println();     
System.out.print("c = ");  System.out.print(c);    
System.out.print(",c binary = ");  
System.out.println(Integer.toBinaryString(c));
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("d = ");  System.out.print(d);    
System.out.print(",d binary = ");  
System.out.println(Integer.toBinaryString(d));
System.out.print("~d = ");  System.out.print(~d);
System.out.print(", ~d binary = ");  
System.out.println(Integer.toBinaryString(~d));
     System.out.println(); 
System.out.print("e = ");  System.out.print(e);    
System.out.print(",e binary = ");  
System.out.println(Integer.toBinaryString(e));
System.out.print("~e = ");  System.out.print(~e);
System.out.print(", ~e binary = ");  
System.out.println(Integer.toBinaryString(~e));
}
}

Result:

The toBinaryString function of Integer class allow You display number binary. The int data type takes 4 bytes so it is 32 chars of string contains representation of integer number. As you notice this operator changes number for opposite. But as you may see opposite for 0 is -1 and opposite for -1 is 0. So opposite number for 1 is -2 and so on. This situation presents diagram below:
The 0 and -1 integer has the same representation
in binary: 11111111 11111111 11111111 11111111.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.