Search code examples
c#c++.net-micro-framework

Converting code segment from C++ to C#


Im trying to convert this segment of c++ code to c#:

  if (latch_state & 0x1) {
    MC->setPin(AIN2pin, HIGH);
  } else {
    MC->setPin(AIN2pin, LOW);
  }

  if (latch_state & 0x2) {
    MC->setPin(BIN1pin, HIGH);
  } else {
    MC->setPin(BIN1pin, LOW);
  }

  if (latch_state & 0x4) {
    MC->setPin(AIN1pin, HIGH);
  } else {
    MC->setPin(AIN1pin, LOW);
  }

  if (latch_state & 0x8) {
    MC->setPin(BIN2pin, HIGH);
  } else {
    MC->setPin(BIN2pin, LOW);
  }

I know enough to convert MC->setPin(PinNum, state) to MC.setPin(pinNum, state) so they are not issue, but I'm confused about the what the if statements would become.

latch_state is of type uint8_t, but it seems to be handled like a byte (which is what I was trying to convert it to) and 0x1 appears also to be a byte.

So how would a binary and operation evaluate in an if statement?

For the conversion, should I do

if ((latch_state & 0x1) == 0x0) or if ((latch_state & 0x1) != 0x0) or something totally different?


Solution

  • if ((latch_state & 0x1) != 0)
    

    should work. Normally, C++ conditions which don't evaluate to a boolean are doing an implicit comparison to 0, with 'true' being that the expression is not 0.