csimdsseabsolute-value

C simd _m128 fabs


How to make fabs() for __m128 vector ?

Does I have to use sign bits to multiply the original vector by 1.0f/-1.0f ?

Didn't find any instruction set to do it.

I don't want __m256 or 512. I'm searching for __m128 data type


Solution

  • A single AND-NOT using a prepared constant to turn off the sign bits suffices:

    #include <stdio.h>
    
    #include <xmmintrin.h>
    
    
    int main(void)
    {
        static const __m128 MinusZero = { -0.f, -0.f, -0.f, -0.f };
    
        __m128 x = { +1, -2, +3, -4 };
    
        __m128 y = _mm_andnot_ps(MinusZero, x);
    
        printf("%g %g %g %g\n", y[0], y[1], y[2], y[3]);
    }
    

    Output:

    1 2 3 4