gpt4 book ai didi

c++ - 左移 << 如何在不同的函数中给出不同的结果?

转载 作者:行者123 更新时间:2023-12-01 22:16:11 25 4
gpt4 key购买 nike

我一直在调试 C++ 库中的问题,发现文字 0变量设置为 0 之间存在奇怪的差异,但仅在库内部。如果我将代码复制到我自己的代码中,它就会按预期工作。

库代码将 1 向下移动一个长整数,以一次屏蔽一位。当发送特定代码(重复键)时,您发送一种虚拟数据包,并且“无位”,因此它传输 header 而不传输数据。我假设如果没有要发送的位,for 循环将跳过循环。

我已将其简化以分解分配,并添加了以下调试。我只是对我添加的 nbits 和文字 0 重复这些步骤。

void  IRsend::sendNEC (unsigned long data,  int nbits){

Serial.println(data, HEX);
Serial.print(" nbits = ");
Serial.println( nbits);
if(nbits == 0) Serial.println("nbits == 0"); else Serial.println("nbits != 0 ");
Serial.print(" 0 - 1 = ");
Serial.println(0 - 1);
Serial.print(" nbits - 1 = ");
Serial.println(nbits - 1);
Serial.print(" (1UL << (0 - 1) = ");
Serial.println(1UL << (0 - 1));
Serial.print(" (1UL << (nbits - 1) = ");
Serial.println(1UL << (nbits - 1));
...

// the part I was originally debugging:
for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) {
...
}

called like:

irsend.sendNEC(0xFFFFFFFF, 0);

这令人惊讶地给出了以下输出:

FFFFFFFF
nbits = 0
nbits == 0
0 - 1 = -1
nbits - 1 = -1
(1UL << (0 - 1) = 0
(1UL << (nbits - 1) = 1

最后两个结果怎么会不同呢? nbit 是 0,那么为什么当文字 0 都以 -1 结束时,它们的移位方式不同(我添加了额外的括号以确保确定)?

为什么当我将完全相同的调试代码复制到调用该库的代码中,并调用如下测试函数时:

void runtest(unsigned long data,  int nbits){
/// same debug ...
}
void setup() {
runtest(0xFFFFFFFF, 0);
}

我得到了预期的输出:

-- Same test again --
FFFFFFFF
nbits = 0
nbits == 0
0 - 1 = -1
nbits - 1 = -1
(1UL << (0 - 1) = 0
(1UL << (nbits - 1) = 0

我只能准确地猜测 0 == 0,例如如果默认为更长的类型 0?

这是使用 Arduino IRRemote 库:https://github.com/z3t0/Arduino-IRremote/blob/master/ir_NEC.cpp

它在 ATmega328 上运行,我可能在 Arduino 1.8.10 IDE 中使用 avr-gcc 在 MacOSX 上构建。

最佳答案

来自 C++ 标准草案 expr.shift :

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the width of the promoted left operand.

您的代码具有未定义的行为,因此任何事情都可能发生。

关于c++ - 左移 << 如何在不同的函数中给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59156677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com