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,

    I think you might have some misunderstandings.

    Regarding the sign bit, the FPU data format is different from the format of the integer.

    In the FPU case, data consists of a sign bit and an absolute value.

    In the integer case, data has 2's complement format.

    Therefore, the absolute value of FPU data can be gotten because the sign bit can be cleared.

    To the contrary, to get the absolute value of the integer there would be 2 steps. The first is to compare with zero. The second is to negate the value if it is a negative value.

    The instruction sequence will be the following and it will take at least 2 cycles.

    cmp r0,#0
    it lt
    neglt r0,r0
    

    Best regards,

    Yasuhiko Koumoto.

Reply
  • Hi,

    I think you might have some misunderstandings.

    Regarding the sign bit, the FPU data format is different from the format of the integer.

    In the FPU case, data consists of a sign bit and an absolute value.

    In the integer case, data has 2's complement format.

    Therefore, the absolute value of FPU data can be gotten because the sign bit can be cleared.

    To the contrary, to get the absolute value of the integer there would be 2 steps. The first is to compare with zero. The second is to negate the value if it is a negative value.

    The instruction sequence will be the following and it will take at least 2 cycles.

    cmp r0,#0
    it lt
    neglt r0,r0
    

    Best regards,

    Yasuhiko Koumoto.

Children