Reading about the integer promotion and integer conversion rank I found this link
- 1.If both operands have the same type, then no further conversion is needed.
- 2.Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer
conversion rank is converted to the type of the operand with greater
- 3.Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then
the operand with signed integer type is converted to the type of the
operand with unsigned integer type.
- 4.Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned
integer type, then the operand with unsigned integer type is converted
to the type of the operand with signed integer type.
- 5.Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
Case 4 applies if you have an unsigned type that is smaller in rank than the signed type it is operating with and they have different sizes. Case 5 then if the two are the same size.
For example, on my system
int is 32-bit,
long is 64-bit, and
long long is 64-bit. If you then have the following:
unsigned int a; // range: 0 to 4294967295 long b; // range: -9223372036854775808 to 9223372036854775807 unsigned long c; // range: 0 to 18446744073709551615 long long d; // range: -9223372036854775808 to 9223372036854775807
For an expression involving
b, which are
unsigned int and
long, any valid
unsigned int can fit in a
a is converted to
long in that situation.
Conversely, For an expression involving
d, which are
unsigned long and
long long, a
long long cannot hold all values of an
unsigned long. So both operands are converted to
unsigned long long.
Regarding what happens during a promotion / conversion on the bit level, let's first assume that the lower rank type is smaller than the higher rank type, and that signed types use 2's complement representation.
For a conversion from a 32 bit
int to a 64 bit
long, if the value is positive, 4 bytes containing all 0 bits are added on the left. If the value is negative, 4 bytes containing all 1 bits are added on the left. For example, the representation of value
5 changes from
0x0000000000000005. For the value
-5, the representation changes from