我已经为USB控制的继电器开关下载了一些source code。我需要为应用程序处理此代码,但在理解字节运算符时遇到了麻烦。
我已经看过移位运算符,并且我知道它们正在将位移至2的下一个幂。下面是我正在努力使用的函数:
byte[] SerBuf = new byte[64];
byte states = 0;
private void button_pressed(object sender, MouseEventArgs e)
{
// Check type of sender to make sure it is a button
if (sender is Button)
{
if (usb_found == 1)
{
Button button = (Button)sender;
// Check the title of the button for which realy we wish to change
// And then check the state of that relay and send the appropriate command to turn it on or off
switch (button.Text.ToString())
{
case "Relay 1":
if ((states & 0x01) == 0) SerBuf[0] = 0x65; //<this is the bit I don't understand
else SerBuf[0] = 0x6F;
//Thread.Sleep(2000);
break;
case "Relay 2":
if ((states & (0x01 << 1)) == 0) SerBuf[0] = 0x66; //<this is the bit I don't understand
else SerBuf[0] = 0x70;
break;
case "Both":
SerBuf[0] = 0x64;
break;
case "None":
SerBuf[0] = 0x6E;
break;
}
transmit(1); // this sends the new buffer to the relay board
}
}
我不了解的是if ((states & 0x01) == 0)
正在评估什么
States
字节在0到3之间,具体取决于两个继电器开关中的哪个处于活动状态。
0x01
在做什么?
答案 0 :(得分:2)
&
运算符是bit-and运算符。它逐位比较两个操作数。仅当位置上的两个位均被置位时,结果中的相应位也被置位。
因此,假设您有a
和b
,其中a
表示为位字符串是00001101
,而b
表示为00001011
。那么写为位字符串的a & b
是00001001
,因为
+----- no bit is set
|+---- both bits are set
||+--- only one bit is set
|||+-- only one bit is set
||||+- both bits are set
vvvvv
a = 00001101
b = 00001011
----------------
a & b = 00001001
因此,换句话说,(states & 0x01) == 0
为真且仅当states
为偶数时,即以位字符串形式写入时,它以0
结尾。请记住,0x01
是00000001
写为位字符串。