Search code examples
cbitwise-operators

How does the bitwise XOR operation work with negative operands?


I'm learning bitwise operation and I came across an xor operation,

#include<stdio.h>
#include<conio.h>
int main
{
    printf("%d\n",10 ^ 9);
    getch();
    return 0;
}

The binary form of 10 ---> 1 0 1 0
The binary form of 9 ---> 1 0 0 1

So, in XOR, the output is 1 when one of the inputs is 1 and the other is 0.

So the output of 10 ^ 9 is 0 0 1 1 => 3

So when trying for the -10 ^ 9, I'm getting the output as -1.

#include<stdio.h>
#include<conio.h>
int main
{
    printf("%d\n",-10 ^ 9);
    getch();
    return 0;
}

Can someone explain to me how it is -1?


Solution

  • Continuing from the comment.

    In a two's complement system, negative values are represented by values that are sign-extended to the width of the type. Where 10 is 1010 in binary, the two-complement representation for -10 for a 4-byte integer is:

    11111111111111111111111111110110
    

    (which has an unsigned value of 4294967286)

    Now you see what happens when you xor with 9 (binary 1001),

      11111111111111111111111111110110
    ^                             1001
    ----------------------------------
      11111111111111111111111111111111  (-1 for a signed integer)
    

    The result is 1111 which is sign-extended to 32-bits, or 11111111111111111111111111111111 for a signed int, which is -1.