سؤال

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 ?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

Seems legit!

1111 1110   (-2)
xor
0000 1010   (10)
=
1111 0100   (-12)

^ is the bitwise XOR, not power

a = 10 = 0000 1010
b = -2 = 1111 1110
──────────────────
a^b    = 1111 0100 = -12
(int) -2 = 0xfffffffe

(int) 10 = 0x0000000a                                  

0xfffffffe ^ 0x0000000a = fffffff4 = (int) -12
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top