标准大小的整数之间的转换是否总是完全由标准定义的? [英] Is conversion between exactly-sized integers always completely defined by the standard?

查看:34
本文介绍了标准大小的整数之间的转换是否总是完全由标准定义的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#include <cstdint>
#include <iostream>
#include <iomanip>

int main()
{
    auto x=std::uint32_t(1)<<31;
    std::cout << " x: 0x" << std::hex << x << " =  " << std::dec << x << "\n";
    int32_t sx=x;
    std::cout << "sx: 0x" << std::hex << sx << " = " << std::dec << sx << "\n";
}

我从中得到以下输出:

 x: 0x80000000 =  2147483648
sx: 0x80000000 = -2147483648

这里 x 的值不能用 int32_t 表示,C++11 标准对这种转换做了如下说明:

Here the value of x can't be represented in int32_t, and the C++11 Standard says the following about this conversion:

如果目标类型是有符号的,如果它可以在目标类型中表示(和位域宽度);否则,该值是实现定义的.

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.

即使使用 intXX_t,这仍然是实现定义的,为此我们对表示有一定的保证吗?如果是,那么我如何保证结果如上图所示?我应该 memcpy 我的无符号值进行签名以获得二进制补码解释,还是有更直接的方法?

Is this still implementation-defined even with intXX_t, for which we have certain guarantees on representation? If yes, then how can I guarantee that the result will be as shown above? Should I memcpy my unsigned value to signed to get two's complement interpretation, or is there a more straightforward way?

推荐答案

int32_t sx=x;实现定义.

您引用的规则是,将值转换为该值超出范围的类型会导致实现定义的行为.

The rule, which you quoted, is that converting a value to a type for which that value is out-of-range causes implementation-defined behaviour.

int32_t 的范围上升到 INT32_MAX,即 2147483647,但 (uint32_t)1 <<<31 比这多 1 个.

The range for int32_t goes up to INT32_MAX which is 2147483647, but (uint32_t)1 << 31 is one more than that.

这与表示无关,而是值是否可以保持不变.

It's nothing to do with representations, it's all about whether the value can remain unchanged or not.

使用 memcpy 将生成 int32_t,它与您从中复制的其他值具有相同的表示(我认为这是明确定义的,因为 int32_t不能有填充或陷阱)

Using memcpy would generate the int32_t which has the same representation as the other value you copy from (I think this is well-defined since int32_t cannot have padding or traps)

这篇关于标准大小的整数之间的转换是否总是完全由标准定义的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆