Why is the output -33 for this code snippet

大兔子大兔子 提交于 2019-12-02 01:43:31

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!