Unsigned and Signed Values in C (Output)

前端 未结 5 2187
攒了一身酷
攒了一身酷 2020-12-15 01:15
signed int x = -5;
unsigned int y = x;

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

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 01:31

    The value of y is UINT_MAX - 5 + 1, i.e. UINT_MAX - 4.

    When you convert signed integer value to unsigned type, the value is reduced modulo 2^N, where N is the number of value-forming bits in the unsigned type. This applies to both negative and positive signed values.

    If you are converting from signed type to unsigned type of the same size, the above means that positive signed values remain unchanged (+5 gets converted to 5, for example) and negative values get added to MAX + 1, where MAX is the maximum value of the unsigned type (-5 gets converted to MAX + 1 - 5).

提交回复
热议问题