请考虑以下代码:
#include <hal_types.h>
int main() {
uint16 crc16; // hal_types.h: typedef unsigned short uint16;
crc16 = 0x43; // debugger: crc16 == 0x0043, as expected
crc16 = crc16 << 8; // crc16 == 0x0000 ????
return 0;
}
此代码在TI CC1111 SoC(带有8051内核)上运行,并使用IAR EW8051 8.10.3进行编译/调试,配置为使用C99方言,无需优化.使用IAR调试器观察注释中的值(使用模拟器或实际设备的结果相同).
我希望在crc16 = crc16<
The integer promotions are performed on each of the operands. The type
of the result is that of the promoted left operand. If the value of
the right operand is negative or is greater than or equal to the width
of the promoted left operand, the behavior is undefined.The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits
are filled with zeros. If E1 has an unsigned type, the value of the result
is E1 × 2^E2, reduced modulo one more than the maximum value representable in
the result type. If E1 has a signed type and nonnegative value, and
E1 × 2^E2 is representable in the result type, then that is the resulting
value; otherwise, the behavior is undefined.
我对此的看法是结果类型应该是无符号的16位整数,其值为((0x0043)*(2 ^ 8))%0x10000 == 0x4300.
我错过了什么吗?谢谢.
最佳答案 我弄清楚发生了什么.即使没有优化,我没有使用crc16的事实似乎改变了语义.如果我在最后添加以下行,
if (crc16)
crc16 = 0x1234;
然后crc16在crc16 = crc16<