8051(8位)微控制器上出现意外的位移结果

8051(8位)微控制器上出现意外的位移结果,第1张

概述请考虑以下代码: #include <hal_types.h>int main() { uint16 crc16; // hal_types.h: typedef unsigned short uint16; crc16 = 0x43; // debugger: crc16 == 0x0043, as expected crc16 请考虑以下代码:

#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<<之后8;,crc16的值为0x4300,而不是0x0000. 根据C99标准(以及2005年5月5日至2005年5月的草案),第6.5.7.3-4节.

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<<之后具有期望值(0x4300). 8 ;.

总结

以上是内存溢出为你收集整理的8051(8位)微控制器上出现意外的位移结果全部内容,希望文章能够帮你解决8051(8位)微控制器上出现意外的位移结果所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1230140.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存