Pregunta

My little program:

#include <stdio.h>

int main() {
    signed char c = -128;
    c = -c;
    printf("%d", c);
    return 0;
}

print:

-128

Is minus (-) operator portable across CPU?

¿Fue útil?

Solución

The operand of the unary minus first undergoes standard promitions, so it is of type int, which can represent the value -128. The result of the operation is the value 128, also of type int. The conversion from int to signed char, being a narrowing of signed types, is implementation-defined.

(Your implementation seems to do a simple wrap-around: 125, 126, 127, -128, -127, ...)

Otros consejos

Note: -128 in 2's complement is 1000 0000 (in one byte) and 128 is also 1000 0000 . If you do char c = 128 and print it it will be -128 because of the following reason:

A char variable = 128 value stores in memory as follows.

MSB
+----+----+----+---+---+---+---+---+
|  1 |  0 | 0  | 0 | 0 | 0 | 0 | 0 |   
+----+----+----+---+---+---+---+---+
   7    6   5    4   3   2   1   0  

Now,

  1. this value will be interpreted as negative value because MSB is 1,
  2. to print magnitude of this -ve number 2's complement needed, that is also 128 in one byte so output is: -128

    2's complement:

      1000 0000
    
      0111 1111  1's complement 
    + 0000 0001 
     -----------
      1000 0000  2's complement   
    
     Magnitude = 128 
     So in one byte 128 == -128
    

because a byte(char) can't hold 128

-128 = 0x80

what neg do is reverse it and plus 1

-(-128) = (~0x80) + 1 = 0x7F + 1 = 0x80

daha, you got 0x80 again

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top