【问题标题】:Creating a loop that toggles a value and stores the new value for further computations创建一个循环来切换一个值并存储新值以供进一步计算
【发布时间】:2012-04-26 14:36:47
【问题描述】:

我正在尝试创建以下循环:

int temp=0x07;

if(left sensor detects){
byteTx((temp)^(1<<0)); //(toggle bit 0)
}

if(right sensor detects){
byteTx((temp)^(1<<2)); //(toggle bit 2)
}

if(front sensor left || front sensor right detects){
byteTx((temp)^(1<<1)); //(toggle bit 1)
}

但是,每个其他 if 语句都会切换正确的值,但会重置其他值(因为 temp 是 0x07)。

问题:我如何确保只切换所需的位,并保持其他位不变,即使它们被其他 if 语句切换。基本上我想存储输出并使用它而不是 temp。

感谢您的帮助,如果您需要更多信息,请告诉我。

编辑

感谢您的回复,但我没有问如何切换,我问的是如何确保切换的值在 IF 语句之间是一致的。

0x07 将继续重置在其他 IF 语句中切换的其他位,我想确保 IF 语句不会重置其他位。

例子

0000 0111 ^(1

但是如果对于另一个 IF 语句:

0000 0111 ^(1

如您所见,结果为 0011,这会将第一条语句中的 0 位变回 1。

我怎样才能防止这种情况发生?

【问题讨论】:

  • 切换,你的意思是清楚吗?因为切换将是byteTx((temp)^(1&lt;&lt;0))
  • 抱歉,我最后一分钟更改了代码,是的,它的切换现在无法修复

标签: c if-statement toggle bit-manipulation sensors


【解决方案1】:

如果您想在切换后临时保持切换的位,您必须通过写回新状态来修改它。 有点像

if(left sensor detects){
   temp=(temp)^(1<<0); //(toggle bit 0)
   byteTx(temp);
}

在循环结束时,temp 将拥有所有切换位。

【讨论】:

    【解决方案2】:

    使用 XOR (^)。

    与 0 进行按位异或以保留旧值
    按位异或与 1 切换旧值

    oldvalue ^ 0x01 /* toggle bit 0 */
    oldvalue ^ 0x02 /* toggle bit 1 */
    ...
    

    【讨论】:

      【解决方案3】:

      您可以使用 XOR 运算符 « ^ »。

      【讨论】:

        【解决方案4】:

        试试这个:

        int temp=0x07;
        
        if(left sensor detects){
            temp ^= 1<<0;
            byteTx(temp); //(toggle bit 0)
        }
        
        if(right sensor detects){
            temp ^= 1<<2;
            byteTx(temp); //(toggle bit 2)
        }
        
        if(front sensor left || front sensor right detects){
            temp ^= 1<<1;
            byteTx(temp); //(toggle bit 1)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多