This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Compiler/MSP430F1611: Bitwise invert and if expression

Part Number: MSP430F1611

Tool/software: TI C/C++ Compiler

Hello,

I have a question due to some weird issues compiling code.

int test(char * header) {
  if (header[0] == ~header[1]) {
    return 0;
  }
  return 1;
}

This code does not work. It does not return 0, if the second byte is the bitwise invertation of the first byte. But the following code DOES work:

int test(char * header) {
  char test[2];
  test[0] = header[0];
  test[1] = ~header[1];
  if (test[0] == test[1]) {
    return 0;
  }
  return 1;
}

Can someone explain me why this is happening?

  • probably because the ~header[1] is returning an int, not a char. You would have to cast it to char: (char)(~header[1]) which will probably give you a warning.
  • You can verify that this is indeed the case by adding the following code:

    size_t t1, t2;

    t1 = sizeof(header1[1]); // t1 = 1;
    t2 = sizeof(~header1[1]); // t2 = 4
  • Yes, thank you.

    I can verify this. When compiling ~header[0] it uses XOR.W -1 and that returns a 16 bit integer instead of char:

    When inverting 0x14 it results in a 0xFFEB instead of 0xEB.

    Adding a cast to (char), (signed char) or (unsigned char) resolved this. Then its assembler code uses XOR.B -1!

    Thank you very much!

**Attention** This is a public forum