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.

Saturated add/sub in C?



Is there an efficient way to do a signed/unsigned 16/32 bit add or sub in C with the C2000 compiler?

In assembly, this is relatively easy by setting the OVM bit and doing the 16 bit add in AH.

Unfortunately, there are no intrinsics for saturated add/sub available.

So when doing this from C, I would write something like

int a,b,c;

asm(" setc SXM, OVM");
c = (int)((((long)a << 16) + ((long)b << 16)) >> 16);

to do the add in AH and save the saturated 16 bit result of c = a+b.

This does not work. The C-Compiler generates this code with -o3:

        setc SXM, OVM
        MOV       ACC,@_a
        ADD       ACC,@_b
        LSL       ACC,16     
        MOVH      @_c << 0

The code does no saturation - the add is performed in the low 16 bit of ACC.

Without optimization, the code is okay:

        setc SXM, OVM
        MOV       ACC,@_a << 16
        MOVL      XAR6,ACC        
        MOV       ACC,@_b << 16
        ADDL      ACC,XAR6
        SFR       ACC,16               
        MOV       @_c,AL

So is there a solution that works with all optimization levels and will work with all future compiler versions?

I would highly appreciate intrinsics for this... - but any other working and efficient solution is okay.