[英]Compare the sign bit in SSE Intrinsics
一個人如何使用SSE內在函數創建一個掩碼,該掩碼指示兩個打包浮點數(__m128's)的符號是否相同,例如,如果比較a和b,其中a為[1.0 -1.0 0.0 2.0],b為[1.0 1.0 1.0 1.0]我們想要的蒙版是[true false true true]。
這是一個解決方案:
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)
在此代碼段中, i
和f
將具有相同的位掩碼。 我假設您要使用__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.
看一下_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
因此,除了第二個向量元素外,符號是相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.