-7

Can anyone explain how x^-1 is being executed in below code. I tried but no luck. I understood how x^1 is being executed.

#include <stdio.h>
int main(void) 
{
int a=220, b=221, c=3;
printf("a^1= %d ,, a^-1= %d \n", a^1, a^-1);
printf("b^1= %d ,, b^-1= %d \n", b^1, b^-1);
printf("c^1= %d ,, c^-1= %d \n", c^1, c^-1);
return 0;
}
/* output: a^1= 221 ,, a^-1= -221
           b^1= 220 ,, b^-1= -222
           c^1= 2   ,, c^-1= -4    */
bmargulies
  • 97,814
  • 39
  • 186
  • 310
viki
  • 37
  • 1
  • 4

2 Answers2

3

The ^ operator is the XOR or exclusive-or operator in C. To make it simple, consider 8-bit signed values, using the typical two's-complement encoding. The int type will work in the same way.

Decimal   Binary
      1   00000001
     -1   11111111
          -------- XOR
     -2   11111110

Note that the unary operator - has higher precedence that the ^ bitwise operator.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

Signed ints use Two's complement in order to represent negative numbers.

1 represented in int32:

0000 0000 0000 0000 0000 0000 0000 0001

-1 represented in int32, using Two's complement:

1111 1111 1111 1111 1111 1111 1111 1111

XORing the two results in:

1111 1111 1111 1111 1111 1111 1111 1110

which, for signed ints, is -2.

for unsigned ints, that would be 2^32 - 2.

nadavvadan
  • 3,930
  • 1
  • 17
  • 29