Why is the output -33 for this code snippet

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

提交回复
热议问题