0

I have the following versions of negating some integer value (in R12) in assembly in msp430 :

inv R12
inc R12

this is according to the manual and I think this will work the same?

inv R12
add #1, R12

But will this work and why not? :

sub #1, R12
inv R12

Still new to this and thank you for any help!

CL.
  • 173,858
  • 17
  • 217
  • 259

1 Answers1

1

INC dst is emulated with ADD #1, dst, so the first two versions are exactly the same.

As for the third version: In the two's complement representation, inverting all bits computes the negative minus one, so you are computing (−x − 1) + 1 or −(x + 1) + 1, which is indeed the same.

And if you want a more practical demonstration, just use brute force:

#include <assert.h>
#include <stdint.h>
#include <stdio.h>

int main()
{
    for (uint32_t i = 0; i < 0x10000; i++) {
        uint16_t input = i;
        uint16_t output1 = (~input) + 1;
        uint16_t output2 = ~(input - 1);
        assert(output1 == output2);
    }
    puts("it works!");
    return 0;
}
CL.
  • 173,858
  • 17
  • 217
  • 259