Explicitly referring to the C standard (I used N
6 Language
6.3 Conversions
6.3.1 Arithmetic operands
6.3.1.3 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.
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.
A brief translation:
1 - If the value can be represented on the target type, it will be.
2 - If they are unsigned
bits will be truncated. (as the other answers say).
3 - If they are signed
, result is defined by the implementation.
The third point is quite important. If you are going to convert a int
for a char
may have unexpected results from your compiler. Although virtually everyone truncates the bits, you should not assume that this always occurs.
Prefer to convert from unsigned int
for unsigned char
when possible.
Got it, thank you very much.
– Giovani
Note that there are processors that store their data in memory differently, so this same operation would have different results, see more on http://pt.wikipedia.org/wiki/Extremidade_%28sort%C3%A7%C3%A3o%29
– lsalamon