c++ - 在 c++ 中,从 unsigned int 到 int 的转换总是保留位模式吗?

标签 c++ casting language-lawyer

从标准 (4.7) 看来,从 int 到 unsigned int 的转换,当它们都使用相同的位数时,纯粹是概念性的:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2 n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]

所以在这个方向上,转换会保留位掩码。我不确定标准是否保证从 unsigned int 到 int 的转换相同(再次,假设使用相同的位数)。这里的标准说:

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.

这里的“目标类型”到底是什么意思?例如 2^32-1 不能用 32 位整数表示。这是否意味着它不能在目标类型中表示,因此不能假设位模式将保持不变?

最佳答案

int 在这种情况下是目标类型。正如您所说,2^32-1 在这种情况下无法表示,因此它是特定于实现的。虽然,我只见过它保留位模式。

编辑:我应该补充一点,在嵌入式世界中,当一个存储位置需要多个位对位相同的表示时,我们经常使用 union 。

在这种情况下

union FOO {
    int32_t signedVal;
    uint32_t unsignedVal;
} var;

var 可以作为 var.signedVal 访问以获取 32 位存储为带符号的 int 和 var.unsignedVal 以获取 32位存储为无符号值。在这种情况下,位将被保留。

关于c++ - 在 c++ 中,从 unsigned int 到 int 的转换总是保留位模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14664896/

相关文章:

c++ - 将 std::function 转换为不同的 std::function 并调用它?

javascript - 寻找一行类型转换 Number(oldValue) += 1;在JS中

c++ - 在 Type 和 Wrapper<Type> 之间 reinterpret_cast 是否安全?

c++ - MFC DDX_Radio 在调用 DoDataExchange 时导致调试断言失败(dlgdata.cpp 第 286 行)

c++ - 没有重载函数的实例 ""匹配参数列表错误

c++ - OpenGL翻译glm右侧还是左侧?

c - gcc 和 clang 中的 C99 支持不一致

c++ - rand 在不改变种子的情况下改变值(value)

java - 转换为字节时 JUnit 出错?

c++ - 当前草案中 [expr.ref]/(4.2) 和 [expr.sub]/1 之间是否存在矛盾?