-3
int main(){
        int a = 10, b = -2;
        printf("\n %d \n",a^b);
        return 0;
}

This program outputs -12. I could not understand how. Please explain.

0111 1110 -> 2's complement of -2
0000 1010 -> 10
---------
0111 0100

This no seems to be greater than -12 and is +ve. But how did I get the o/p as -12 ?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Angus
  • 12,133
  • 29
  • 96
  • 151

4 Answers4

2

To find the two's complement of a negative integer, first find the binary representation of its magnitude. Then flip all its bits, i.e., apply the bitwise NOT operator !. Then add 1 to it. Therefore, we have

2       -->  0000 0000 0000 0010
~2      -->  1111 1111 1111 1101  // flip all the bits
~2 + 1  -->  1111 1111 1111 1110  // add 1

Therefore, the binary representation of -2 in two's complement is

1111 1111 1111 1110

Now, assuming the size of int is 4, the representation of a and b in two's complement is -

a -->        0000 0000 0000 1010  --> 10
b -->        1111 1111 1111 1110  --> -2
a^b -->      1111 1111 1111 0100  --> -12

The operator ^ is the bitwise XOR, or exclusive OR operator. If operates on the corresponding bits of a and b and evaluates to 1 only when the bits are not both 0 or both 1, else it evaluate to 0.

ajay
  • 9,402
  • 8
  • 44
  • 71
  • 1111 1111 1111 0100 - Is this no -12 ?. what happened to the bits set before it. If MSB is set with 1, we consider it as a minus no. What happens to the bits set from 5th bit till the 15th bit. – Angus Apr 26 '14 at 10:21
  • @Angus that's sign extension. `10100` is -12 and adding the sign bit to the left of the number doesn't change its value – phuclv Apr 26 '14 at 10:24
  • @Angus Here's the rule. If the MSB is `1`, then the number is negative. To get its modulus, flip all the bits and add 1. – ajay Apr 26 '14 at 10:26
  • @Roma-MT Yes, `(!(a^b))+1` would give the magnitude since `a^b` is negative. – ajay Apr 26 '14 at 10:30
  • @Lưu Vĩnh Phúc: I couldnt still get it. can you please explain in detail. – Angus Apr 26 '14 at 10:31
  • 1
    @ajay add it to your answer ! it will be helpful for future users ! – Coldsteel48 Apr 26 '14 at 10:33
  • @Ajay: Thanks. I could get why -12. – Angus Apr 26 '14 at 10:38
  • 1
    @ajay the bitwise not should be `~`, not `!`. So that's `~2 + 1` – phuclv Apr 29 '14 at 07:26
  • @LưuVĩnhPhúc Yes, right! I somehow mixed it. fixed now. Thanks much :) – ajay Apr 29 '14 at 07:50
2

Seems legit!

1111 1110   (-2)
xor
0000 1010   (10)
=
1111 0100   (-12)
Coldsteel48
  • 3,482
  • 4
  • 26
  • 43
1

^ is the bitwise XOR, not power

a = 10 = 0000 1010
b = -2 = 1111 1110
──────────────────
a^b    = 1111 0100 = -12
phuclv
  • 37,963
  • 15
  • 156
  • 475
0
(int) -2 = 0xfffffffe

(int) 10 = 0x0000000a                                  

0xfffffffe ^ 0x0000000a = fffffff4 = (int) -12
Gwenc37
  • 2,064
  • 7
  • 18
  • 22
hasan
  • 638
  • 4
  • 14