了解If语句字节运算符

时间:2019-05-01 17:16:11

标签: c# byte

我已经为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在做什么?

1 个答案:

答案 0 :(得分:2)

&运算符是bit-and运算符。它逐位比较两个操作数。仅当位置上的两个位均被置位时,结果中的相应位也被置位。

因此,假设您有ab,其中a表示为位字符串是00001101,而b表示为00001011。那么写为位字符串的a & b00001001,因为

           +----- 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结尾。请记住,0x0100000001写为位字符串。