Why is the output -33 for this code snippet

前端 未结 3 1114
没有蜡笔的小新
没有蜡笔的小新 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.

    0 讨论(0)
  • 2021-01-23 06:25

    You should print out unsigned integers with the %u specifier:

    unsigned int a = 32;
    printf("%u\n", ~a);
    

    Printing it out with %d treats it as a signed integer.

    You see it as a negative number because the sign bit is set from 0 to 1 through the binary negation.

    Printing it out as a hex number doesn't interpret the sign bit, so you see the same result in both cases.

    0 讨论(0)
  • 2021-01-23 06:26

    Most computers use two's complement representation for negative numbers. See here: http://en.wikibooks.org/wiki/A-level_Computing/AQA/Problem_Solving,_Programming,_Data_Representation_and_Practical_Exercise/Fundamentals_of_Data_Representation/Two%27s_complement

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