Unsigned and Signed Values in C (Output)

前端 未结 5 1185
余生分开走
余生分开走 2020-12-15 01:21
signed int x = -5;
unsigned int y = x;

What is the value of y? How is this so?

5条回答
  •  臣服心动
    2020-12-15 01:54

    It depends on the maximum value of the unsigned int. Typically, a unsigned int is 32-bit long, so the UINT_MAX is 232 − 1. The C standard (§6.3.1.3/2) requires a signed → unsigned conversion be performed as

    Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

    Thus y = x + ((232 − 1) + 1) = 232 − 5 = 4294967291.


    In a 2's complement platform, which most implementations are nowadays, y is also the same as 2's complement representation of x.

    -5 = ~5 + 1 = 0xFFFFFFFA + 1 = 0xFFFFFFFB = 4294967291.

提交回复
热议问题