3

可能重复:
当二元运算符任一侧的符号不同时,提升规则如何工作?

unsigned整数转换为signed整数时,我知道变量位的表示会发生变化。例如,从 转换为 时,255 可能变为uint8-1 int8。但是,我从来不确定底层位本身的“转换”或“转换”是什么。

我的问题是,整数变量的原始位模式是否保证在有static_cast符号和无符号类型之间保持不变,或者它是否有可能通过强制转换以某种方式进行转换?

出于好奇,static_cast整数标志类型之间是否会生成程序集,还是仅用于编译器知道要生成哪些 asm 指令?

编辑:

这是我想知道的那种场景的示例:

unsigned int uintvar = random();
unsigned int control = uintvar;
assert(control == static_cast<unsigned int>(static_cast<signed int>(uintvar)));

忽略双重演员会被优化掉的事实,这个例子能保证永远成立吗?

4

2 回答 2

8

The bit pattern doesn't change at all (on most architectures you're likely to encounter in practice). The difference is in the instructions generated by the compiler to manipulate the values.

于 2013-01-21T22:16:47.540 回答
4

If the unsigned value is too large to fit inside the signed counterpart then it's undefined behavior.

255 becomes -1 because those bits are -1 in two's compliment. Nothing happens with the bits.

于 2013-01-21T22:17:37.093 回答