A. Sarid A. Sarid - 1 year ago 95
C Question

converting from unsigned long long to unsigned int

I was searching around a little trying to find an answer to this, but I couldn't find a clear cut answer.

I saw this answer where he wrote as a side note:

The rules are different for unsigned types; the result of converting a
signed or unsigned integer to an unsigned type is well defined.

So what is the well defined behavior?

When converting from
unsigned long long
unsigned int
is there a defined behavior? Is it just cutting off the 32 MSB's? (leaving me with the 32 LSB's).

Lets assume that
sizeof(unsigned int)
sizeof(unsigned long long)
in my system.

Is there a different behavior when assigning without casting and when assigning with casting?

Answer Source

The standard says: Signed and unsigned integers
1 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.
2 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)
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

Point 2 describes a modulo operation, which has the same effect than cutting off the MSBs in this case. (It has the same effect when the maximum value of the new type plus one is a power of the number base.)

There's no difference if you use casting.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download