Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Bitwise complement operator
1. Page 1 of 2
Bitwise complement operator (tilde ~) in Java language
Problem: Let integer a=1. Find ~a using a Java program.
Program:
class tilde
{
public static void main(String args[])
{
byte a =1; //Here 1B memory is sufficient. Hence use ‘byte’ data type.
System.out.println("Complement of ” + a + “ is “ + ~a);
}
}
Output:
Complement of 1 is -2
Discussion #1 (How the output is -2?)
Step-1: Here ‘a’ = 1, a positive number. So, find 1's complement of ‘a’.
Binary equivalent of ‘a’ = (00000001)2
1’s complement of ‘a’ = (11111110)2 => (254)10
The Leftmost bit (Most Significant Bit, MSB) of the result is 1 (i.e. negative). Hence, remember
the sign of the result and proceed to Step-2.
Step-2: Find 2's complement of the result obtained in Step-1.
2's complement of a number can be obtained by adding 1 to the 1's complement of that number.
Result of Step-1 = (254)10
Binary equivalent of (254)10 = (11111110)2
1’s complement (254)10 = (00000001)2
Add 1 = (00000001)2
2's complement of (254)10 = (00000010)2 => (2)10
Step-3: Compute the Final result.
Remembering the sign from Step-1 & value from Step-2
Final Result = -2
2. Page 2 of 2
Discussion #2 (What if ‘a’ is a negative number?)
Assume: a = -3
Step-1: Here ‘a’ is a negative number. So, find 2's complement of ‘a’.
Binary equivalent of (3)10 = (00000011)2
1’s complement of (3)10 = (11111100)2
Add 1 = (00000001)2
= (11111101)2 => 2’s complement
Step-2: Find 1's complement of the result obtained in Step-1.
Result of Step-1 = (11111101)2
1’s complement = (00000010)2 => (2)10
The MSB of the result is 0. Hence, the result is a positive number.
Final Result = 2
Observations:
1. The sign of the output will be the opposite of that of the input.
2. We can guess the output easily. If ‘n’ is the input, the output should be -(n+1).
Examples:
a. n = 0, ~n = -1
b. n = -5, ~n = 4