为什么 uint16_t 在这里有所不同?
volatile uint16_t r;
unsigned char poly = 0x07;
unsigned char c = 0;
r = (c << 8) ^ poly;
当代码在 Linux 上使用 gcc 编译时,r
为 7
。
当Microchip C18编译相同的代码时,r
为0
。
为什么?
如果我将其更改为:
volatile uint16_t r;
uint16_t poly = 0x07;
uint16_t c = 0;
r = (c << 8) ^ poly;
在 C18 中,r
也会变为 7
。
C18手册中有关于整数提升的部分,但我认为它与我的问题无关。无论如何,这里是:
ISO 要求所有算术都以 int 精度或更高精度执行。 默认情况下,MPLAB C18 将执行 以最大的尺寸进行算术 操作数,即使两个操作数都是 小于 int。 ISO 规定 行为可以通过 -Oi 设置 命令行选项。
volatile uint16_t r;
unsigned char poly = 0x07;
unsigned char c = 0;
r = (c << 8) ^ poly;
When the code is compiled with gcc on Linux, r
is 7
.
When the same code is compiled by Microchip C18, r
is 0
.
Why?
If I change it to:
volatile uint16_t r;
uint16_t poly = 0x07;
uint16_t c = 0;
r = (c << 8) ^ poly;
r
becomes 7
in C18, too.
There is a section about integer promotion in the C18 manual, but I don't think it has something to do with my question. Anyway, here it is:
ISO mandates that all arithmetic be performed at int precision or greater.
By default, MPLAB C18 will perform
arithmetic at the size of the largest
operand, even if both operands are
smaller than an int. The ISO mandated
behavior can be instated via the -Oi
command-line option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
c << 8
在此编译器中未定义,无法预测异或的结果。结果可以是编译器选择的任何结果。请参阅每个 C 程序员应该了解的关于未定义行为的知识< /a> 有关未定义行为的介绍,特别是“超大班次金额”部分。
Since
c << 8
is undefined in this compiler, the result of xor can't be predicted. The result could be anything the compiler chooses.See What Every C Programmer Should Know About Undefined Behavior for an introduction to undefined behavior, especially the section "Oversized Shift Amounts".
c << 8 与 ca char 基本上将所有位发送到遗忘。正如文档中所指定的,c 和 8 都适合 char,因此一切都是使用 char 完成的。
c << 8UL可能会改变交易。
c << 8 with c a char is basically sending all the bits to oblivion. As specified in the doc, both c and 8 fit in a char, so everything is done using char.
c << 8UL may change the deal.