问题
I am trying to write the equivalent of an if statement with SSE intrinsics.
I am using __m128 _mm_cmplt_ps(__m128 a, __m128 b)
to do the comparison a < b, and this returns 0xffffffff
or 0x0
if the comparison was respectively true or false. I would like to convert these values into 1 and 0. In order to do this, is it correct to implement the logical "and" __m128 _mm_and_ps(__m128 c , __m128 d)
, where c
is the result of the conversion and d
is, e.g., 0xffffffff
?
Thank you for your attention.
回答1:
You're comparing to get a 1
or a 0
, then multiplying by another number. That is essentially this:
c = (a < b) * d;
which is the same as this:
c = 0;
if (a < b)
c = d;
This is also known as a conditional move.
If that's what you want, then you don't need the 0
or the 1
. Just AND the result of the compare directly with the number you will multiply with.
__m128 c = _mm_cmplt_ps(a,b);
c = _mm_and_ps(c,d);
This works because the comparison returns either all 0
's or all 1
's. So ANDing them with the result will either zero it, or keep it entirely.
It was intentionally designed that way. There's no need for a multiplication.
来源:https://stackoverflow.com/questions/13256983/sse-comparison-intrinsics-how-to-get-1-or-0-from-a-comparison