Wednesday, July 10, 2013

One's Complement Operator in C

This operator is a unary operator. It just takes one value and performs one's complement on the number.

For example,
x=~3;
It takes the binary representation of the 3,
3 - 0011



As we need to perform complement of the number, we have to consider all the bits of the number i.e., the number 3 is represented as 0000 0011.

Performing the one's complement results in 1111 1100. It gives the value with the sign bit changed. So, the number is a negative number.

Note: Sign is the most significant bit.

In C, the negative numbers are represented in two's complement form. So to know the number, we have to get the number which is represented in the same form, we got when performed two's complement on it.

To such a number, again we need to perform 2's complement on the result without changing the sign bit.

1's complement of result - 1000 0011
Adding 1 to result          -                 1

The result is                   -  1000 0100 which is nothing but -4.

Thus the result of the one's complement of 3 is -4.

You can better understand the logic by checking the following  program.

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a;
  5. printf("Enter number for a");
  6. scanf("%d", &a);
  7. printf("Ones complement is %d", ~a);
  8. return 0;
  9. }
Give different values to a and check for the results, you will understand.