What is -(-128) for signed single byte char in C?

后端 未结 3 1135
再見小時候
再見小時候 2021-01-18 06:45

My little program:

#include 

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

prin

相关标签:
3条回答
  • 2021-01-18 07:28

    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
      
    0 讨论(0)
  • 2021-01-18 07:42

    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

    0 讨论(0)
  • 2021-01-18 07:49

    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, ...)

    0 讨论(0)
提交回复
热议问题