C++ Converting unsigned to signed integer portability

£可爱£侵袭症+ 提交于 2020-01-17 01:21:27

问题


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


回答1:


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.




回答2:


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>.



来源:https://stackoverflow.com/questions/22623453/c-converting-unsigned-to-signed-integer-portability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!