signed int x = -5;
unsigned int y = x;
What is the value of y
? How is this so?
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.
From the C99 standard:
6.3.1.3 Signed and unsigned integers
- When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
- 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. 49)
49) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
So you'll be looking at, effectively, y = x + UINT_MAX + 1
.
This just happens to mean that the twos-complement representation is used unchanged as an unsigned integer, which makes this very fast on most modern computers, as they use twos-complement for signed integers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With