简体   繁体   English

C++ 将无符号转换为有符号整数的可移植性

[英]C++ Converting unsigned to signed integer portability

I know that in C the conversion of unsigned to signed integers is implementation defined, but what is it for C++?我知道在 C 中,无符号到有符号整数的转换是实现定义的,但是 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;我通过转换为类似于int num = -6; unsigned ret = func((unsigned)num); int ret_as_signed = (int)ret;无符号来传递该函数一个有符号整数int num = -6; unsigned ret = func((unsigned)num); int ret_as_signed = (int)ret; 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.在 Visual Studio 中运行良好,但我想知道它的便携性如何。

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

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> .您可能可以使用<limits>的模板对此进行概括。

Since C++20 finally got rid of ones' complement and sign-magnitude integers, conversion between signed and unsigned integers is well-defined and reversible.由于 C++20 最终摆脱了 1 的补码和符号大小整数,有符号和无符号整数之间的转换是明确定义和可逆的。 All standard integer types are now 2's complement and conversion between signed and unsigned does not alter any bits in the representation.所有标准整数类型现在都是 2 的补码,并且有符号和无符号之间的转换不会改变表示中的任何位。

For versions of C++ prior to C++20, the original answer still applies.对于 C++20 之前的 C++ 版本,原始答案仍然适用。 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] [1]

C++ standard, [conv.integral], § 4.7/3: C++ 标准,[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. [1] 似乎它会起作用,但不能保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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