Why is the output -33 for this code snippet

前端 未结 3 1113
没有蜡笔的小新
没有蜡笔的小新 2021-01-23 05:54
#include

int main()
{
    int a=32;
    printf(\"%d\\n\", ~a);  //line 2
    return 0;
}

o/p = -33

Actually in the original snippet li

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-23 06:12

    In your C implementation, as in most modern implementations of any programming language, signed integers are represented with two’s complement.

    In two’s complement, the high bit indicates a negative number, and the values are encoded as in these samples:

    Bits  Decimal
    0…011 +3
    0…010 +2
    0…001 +1
    0…000  0
    1…111 -1
    1…110 -2
    1…101 -3
    

    Thus, if the usual (unsigned) binary value for the bits is n and the high bit is zero, the represented value is +n. However, if the high bit is one, then the represented value is n-2w, where w is the width (the number of bits in the format).

    So, in an unsigned 32-bit format, 32 one bits would normally be 4,294,967,295. In a two’s complement 32-bit format, 32 one bits is 4,294,967,295 - 232 = -1.

    In your case, the bits you have are 1111 1111 1111 1111 1111 1111 1101 1111. In unsigned 32-bit format, that is 4,294,967,263. In two’s complement, it is 4,294,967,263 - 232 = -33.

提交回复
热议问题