Question

I know that in C the conversion of unsigned to signed integers is implementation defined, but what is it for C++? I figured someone would have asked this already, and I searched but I couldn't find it.

I have a function that operates on an unsigned integer and returns a related unsigned integer. I am passing that function a signed integer by casting to unsigned similar to int num = -6; unsigned ret = func((unsigned)num); int ret_as_signed = (int)ret;. In Visual Studio that works fine, but I wonder how portable it is.

Is there a portable way to convert unsigned integers to signed integers? It it possible to just reverse how signed integers are converted to unsigned via wraparound? Thanks

Was it helpful?

Solution 2

Since C++20 finally got rid of ones' complement and sign-magnitude integers, conversion between signed and unsigned integers is well-defined and reversible. All standard integer types are now 2's complement and conversion between signed and unsigned does not alter any bits in the representation.

For versions of C++ prior to C++20, the original answer still applies. I'm leaving it as a historical remnant.


Conversion of an unsigned integer to a signed integer where the unsigned value is outside of the range of the signed type is implementation-defined. You cannot count on being able to round-trip a negative integer to unsigned and then back to signed. [1]

C++ standard, [conv.integral], § 4.7/3:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

[1] It seems likely that it will work, but there are no guarantees.

OTHER TIPS

For the portable version of the inverse of signed->unsigned conversion, how about:

if ( ret <= INT_MAX )
    ret_as_signed = ret;
else
    ret_as_signed = -(int)(UINT_MAX - ret) - 1;

You could probably generalize this using the templates in <limits>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top