Search code examples
assemblyarmbit-manipulationtwos-complement

How get two's complement of a register value in ARM?


Say I have a 32 bit signed int in register v1. I want to get the two's complement of this value to store in another register v2. In normal math that means I need to flip all 32 bits and then add 1.

How do I flip the bits?


Solution

  • Try this, (MVN move with not):

    MVN v2, v1
    

    This "flips the bits" like you asked. Then you just do the +1:

    ADD v2, v1, #1
    

    Alternatively you can just use the NEG v2, v1 instruction (a short-hand for RSB v2, v1, #0) to do the equivalent operation in a single instruction.