Reputation: 5379
I wonder about type conversion from a smaller signed integer to a larger unsigned integer. It appears that the compiler first converts the signed integer to a signed integer of the same size as the destination, then to the unsigned integer.
Regard the following C++ code:
#include <assert.h>
#include <iostream>
typedef int sint;
typedef unsigned __int64 luint;
int main(int, char**) {
assert(sizeof(luint) > sizeof(sint));
sint i = -10;
luint j = i;
std::cout << std::hex << j;
}
Under Visual C++ this yields: fffffffffffffff6
.
This is as I like it. Can I be sure that all compilers will behave this way? If the signed integer would be converted to an unsigned first and then to the new size, the result would have been fffffff6
.
Upvotes: 0
Views: 229
Reputation: 4760
Signed to unsigned conversion uses modulo 2n arithmetic. From the C++11 Standard, section 4.7 Integral conversions [conv.integral] (§4.7/2):
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).
So j
takes the value 264 − 10, which is 0xfffffffffffffff6
.
Upvotes: 3