简体   繁体   中英

C++ signed integer conversion to unsigned with more bits

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 .

Signed to unsigned conversion uses modulo 2 n 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 2 n where n is the number of bits used to represent the unsigned type).

So j takes the value 2 64 − 10, which is 0xfffffffffffffff6 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM