比较SSE内在函数中的符号位

时间:2011-12-09 03:39:33

标签: c++ sse intrinsics

如何使用SSE内在函数创建一个掩码,指示两个打包浮点(__m128)的符号是否相同,例如比较a和b,其中a为[1.0 -1.0 0.0 2.0]且b为[1.0 1.0] 1.0 1.0]我们得到的所需面具是[true false true true]。

2 个答案:

答案 0 :(得分:5)

这是一个解决方案:

const __m128i MASK = _mm_set1_epi32(0xffffffff);

__m128 a = _mm_setr_ps(1,-1,0,2);
__m128 b = _mm_setr_ps(1,1,1,1);

__m128  f = _mm_xor_ps(a,b);
__m128i i = _mm_castps_si128(f);

i = _mm_srai_epi32(i,31);
i = _mm_xor_si128(i,MASK);

f = _mm_castsi128_ps(i);

//  i = (0xffffffff, 0, 0xffffffff, 0xffffffff)
//  f = (0xffffffff, 0, 0xffffffff, 0xffffffff)

在此代码段中,if都将具有相同的位掩码。我假设您需要__m128类型,因此我添加了f = _mm_castsi128_ps(i);以将其从__m128i转换回来。

请注意,此代码对零符号敏感。因此0.0-0.0会影响结果。


<强>说明:

代码的工作方式如下:

f = _mm_xor_ps(a,b);       //  xor the sign bits (well all the bits actually)

i = _mm_castps_si128(f);   //  Convert it to an integer. There's no instruction here.

i = _mm_srai_epi32(i,31);  //  Arithmetic shift that sign bit into all the bits.

i = _mm_xor_si128(i,MASK); //  Invert all the bits

f = _mm_castsi128_ps(i);   //  Convert back. Again, there's no instruction here.

答案 1 :(得分:2)

查看_mm_movemask_ps指令,该指令从4个浮点数中提取最高有效位(即符号位)。见http://msdn.microsoft.com/en-us/library/4490ys29.aspx

例如,如果您有[1.0 -1.0 0.0 2.0],则movemask_ps将返回4或二进制的0100。那么如果你为每个向量得到movemask_ps并比较结果(可能是按位非异或),那么这将表明所有符号是否相同。

a = [1.0 -1.0 0.0 2.0]
b = [1.0 1.0 1.0 1.0]
movemask_ps a = 4
movemask_ps b = 0
NOT (a XOR b) = 0xB, or binary 1011

因此除了第二个向量元素外,符号是相同的。