Search code examples
cinthexsigned

Hexadecimal value equal to negative value


What 16-bit hexadecimal signed int value works with this code:

#include <stdio.h>

int main() {
  while (1) {
    int i;
    if (scanf("%x", &i) != 1) break;
    printf("%d %s -%d\n", i, (i == -i) ? "==" : "!=", i); 
  }
  return 0;
}

There must be some value with which this returns "==", other than "0".


Solution

  • 8000 (hex) would be the answer (on a 16-bit machine).

    It's because when you negate 8000 in 2's complement, you take the complement plus 1, so that's 7FFF + 1 or back to 8000. In decimal representation, the number is, -32768.

    In the case of the given code, this would be true if an int is 16 bits for the given compiler and processor. Otherwise, i would need to be declared as short int or just short.