【发布时间】:2015-07-14 23:47:58
【问题描述】:
具有以下真值表的布尔运算序列是什么:
mask | target | result
======================
0 | 0 | 0
0 | 1 | 0
1 | 0 | 1
1 | 1 | 0
简而言之,就是“掩码位为真时切换,掩码位为假时清除”。
现在一些上下文:
我正在使用 Arduino 设计转向信号,并且我正在使用位掩码设置当前闪烁的灯,仅使用两个位:
typedef enum ACTIVE_LIGHTS {
NONE = 0, // 00
RIGHT_LIGHT = 1, // 01
LEFT_LIGHT = 2, // 10
BOTH = 3 // 11
};
现在有一个要求是:当我运行 toggleLeft() 方法时,我想清除右侧位,并切换左侧位。
我尝试了两种方法,但都没有按预期工作(遮罩总是 RIGHT_LIGHT 或 LEFT_LIGHT):
target ^= mask; //this toggles one side but doesn't turn the other off
target = mask; //this turns other side off, but never turns off same side
【问题讨论】:
标签: language-agnostic bit-manipulation bitwise-operators boolean-logic bitmask