Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

Actually the hexadecimal numbers 0x8, 0x4, 0x2, 0x1 are 1000, 0100, 0010, 0001 in binary. The way in which are used in your code reminds me of masks. Their only purpose is to "turn off" all bits of the original byte except the one they have "on". For example:

If `latch state == 0x1', then only the first conditional will be true.

Between the two answers you provided, I consider the second one to be right. You need the resulting number not to be 0. However, isn't that what the if statement does anyway?

I hope this helps... :D

To directly convert without reordering your if-blocks, you would use the second option:

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

If the bit is set, the result will be non-zero, which evaluates to a logical truth. So you want to test that the result is not zero. The above is equivalent to this statement in C or C++:

if (latch_state & 0x1)

By the way, picking up on other things you said, it's quite normal to think of any 8-bit unsigned integer as a 'byte'. So don't worry about any 'conversion' that might be taking place. It's the same thing.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top