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

后端 未结 3 1162
再見小時候
再見小時候 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
      

提交回复
热议问题