Explicitly referencing 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 an 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.
3 Otherwise, the new type is signed and the value can not 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 in the target type, it will be.
2 - If they are unsigned
will occur truncation of the bits. (as the other answers say).
3 - If they are signed
, result is defined by implementation.
The third point is quite important. If you convert a int
to a char
it may have unexpected results from your compiler. Although virtually all truncate the bits, you should not assume that this always occurs.
Prefer to convert from unsigned int
to unsigned char
when possible.