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.

Problem with CMP instruction on MSP430F5529?

Other Parts Discussed in Thread: MSP430F5529

I recently came across the following problem when writing assembly for MSP430F5529:


When I do  CMP #0,R4  where R4 contains #0xFFED, I get the Negative bit set. I found out that if R4 contains for example 0xFFFF the negative bit doesn't get set.

I mean, since CMP is a simulated subtraction DST-SRC, subtracting zero from anything positive should never set the negative bit.

Why is this happening? And how then I reliably do an unsigned comparison? I just need to determine if the number in some register is greater than or equal any of these constants: 0x7FFF, 0xFFFF and 0xFFED.

Thanks for any hints!

  • The same CMP (and indeed SUB or ADD) instruction is used whether the operands are considered to be signed or unsigned.

    The distinction between the two is made when checking the status register flags. Jump if higher or same (JHS) and jump if lower (JLO) are intended for use with unsigned values. Jump if greater or equal (JGE) and jump if less (JL) are intended for signed values. If you compare the descriptions of those instructions in the User's Guide you'll see that the unsigned versions just check the C bit, while the signed versions check (N xor V).

  • If you are not sure about the details of an assember instruction, you can always check what the compiler would do:

    $ cat cmp.c
    void f(unsigned int a, unsigned int b)
    {
    	if (a < b)
    		asm("nop");
    }
    $ msp430-gcc -Os -S cmp.c
    $ cat cmp.s
    ...
    	; start of prologue
    	; end of prologue
    	CMP.W	R13, R12 { JHS	.L2
     ; 4 "cmp.c" 1
    	nop
     ; 0 "" 2
    .L2:
    	; start of epilogue
    	RET
    ...

  • N: Set if result is negative (msb is set)
    Z: Set if result is zero , reset otherwise 
    C: Set if there is a carry from the MSB, reset otherwise
    V: Set if the subtraction goes passed the signed-numbers boundry

    compare with zero is what the emulated instruction tst does.

    The results is indeed "negative", or correctly stated: The result does indeed have msb set.
    It's up to you to treat numbers as signed or not, by using JLO vs JL or JHS vs JGE

    So you can use this side effect and using signed numbers status flags on values for what is to you is unsigned numbers.
    like N is set if byte does have a value from 128-255,or V is set of it the byte was  0-127 and now went above 127

  • Many thanks for your responses. I actually didn't know about the JHS and JLO instructions, I used JGE and JL only. Now, I changed them and everything works correctly.

    Best Regards

    Lukas

**Attention** This is a public forum