gpt4 book ai didi

c++ - 精确大小的整数之间的转换是否总是完全由标准定义?

转载 作者:行者123 更新时间:2023-11-30 01:46:40 25 4
gpt4 key购买 nike

考虑以下代码:

#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 标准对这种转换有如下规定:

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 我的无符号值进行签名以获得二进制补码解释,还是有更直接的方法?

最佳答案

int32_t sx=x;实现定义的

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

int32_t 的范围上升到 INT32_MAX这是2147483647 ,但是 (uint32_t)1 << 31比那个多一个。

这跟representations没关系,关键是这个值能不能保持不变。

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

关于c++ - 精确大小的整数之间的转换是否总是完全由标准定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com