c# - 了解 If 语句字节运算符
问题描述
我已经下载了一些USB 控制继电器开关的源代码。我需要为应用程序操作此代码,但无法理解字节运算符。
我看过移位运算符,我知道它们正在将位移位到 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
做什么?
解决方案
&
运算符是位与运算符。它逐位比较两个操作数。只有当一个位置的两个位都被设置时,结果中的相应位才会被设置。
因此,假设您有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
写为位字符串。