Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signed to unsigned conversion in C++

In C++, does the result of the conversion of a signed integral value, to an unsigned integral value, that can be of two different sizes (ex: short int to unsigned long long int, or long long int to unsigned char) is well defined by the standard and platform independent (regardless of how signed integer are represented for example)?

like image 654
Vincent Avatar asked Oct 23 '15 16:10

Vincent


1 Answers

Yes, the value is defined and independent of the representations used. [conv.integral]/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).

Obviously, the size of the destination type matters, though; long long to unsigned char might yield a different value than long long to unsigned int.

like image 145
Columbo Avatar answered Sep 21 '22 17:09

Columbo