从标准 (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/