This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

How to get absolute value of a 32-bit signed integer as fast as possible?

Hi.

I wonder how to calculate absolute value of a 32-bit signed integer in C as fast as possible. I saw that there is a FPU instruction VABS.F32, which do that in one cycle (above the floats). I thought, if it is possible to use it also with integers (sign bit is in both cases MSB bit). Maybe in some way with inline or embedded assembly?

Or do you have any other advice how to get absolute value of an integer in C in the fastest way.

Not to forget - I am speaking regarding Cortex-M4 processor.

Thanks

Parents
  • Hi matic and Yasuhiko,

    If the original value needs to be preserved, below is Example 3.1 from section 3.3.7. Conditional execution of Cortex-M4 Devices Generic User Guide.

    Example 3.1 shows the use of a conditional instruction to find the absolute value of a number. R0 = abs(R1).

    Example 3.1. Absolute value

        MOVS    R0, R1          ; R0 = R1, setting flags

        IT      MI              ; skipping next instruction if value 0 or positive

        RSBMI   R0, R0, #0      ; If negative, R0 = -R0

    For both the negate and reverse subtract instructions, we have to handle the special case when the input is 0x80000000 (sign bit=1, all others are 0; -2147483648). We have to check the behavior of the flags particularly V (overflow).

    Regards,

    Goodwin

Reply
  • Hi matic and Yasuhiko,

    If the original value needs to be preserved, below is Example 3.1 from section 3.3.7. Conditional execution of Cortex-M4 Devices Generic User Guide.

    Example 3.1 shows the use of a conditional instruction to find the absolute value of a number. R0 = abs(R1).

    Example 3.1. Absolute value

        MOVS    R0, R1          ; R0 = R1, setting flags

        IT      MI              ; skipping next instruction if value 0 or positive

        RSBMI   R0, R0, #0      ; If negative, R0 = -R0

    For both the negate and reverse subtract instructions, we have to handle the special case when the input is 0x80000000 (sign bit=1, all others are 0; -2147483648). We have to check the behavior of the flags particularly V (overflow).

    Regards,

    Goodwin

Children
No data