How do I convert _m128i to an unsigned int with SSE?

送分小仙女□ 提交于 2019-12-04 13:36:13

问题


I have made a function for posterizing images.

// =(
#define ARGB_COLOR(a, r, g, b) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))

inline UINT PosterizeColor(const UINT &color, const float &nColors)
{
    __m128 clr = _mm_cvtepi32_ps(  _mm_cvtepu8_epi32((__m128i&)color)  );

    clr = _mm_mul_ps(clr,  _mm_set_ps1(nColors / 255.0f)  );
    clr = _mm_round_ps(clr, _MM_FROUND_TO_NEAREST_INT);
    clr = _mm_mul_ps(clr, _mm_set_ps1(255.0f / nColors)  );

    __m128i iClr = _mm_cvttps_epi32(clr);

    return ARGB_COLOR(iClr.m128i_u8[12],
                      iClr.m128i_u8[8],
                      iClr.m128i_u8[4],
                      iClr.m128i_u8[0]);
}

in the first line, I unpack the color into 4 floats, but I can't find the proper way to do the reverse.

I searched through the SSE docs and could not find the reverse of _mm_cvtepu8_epi32

does one exist?


回答1:


Unfortunately, there's no instruction to do that even in AVX (none that I'm aware of). So you will have to do it manually like are right now.

However, your current method is very sub-optimal and you're relying on .m128i_u8 which is an MSVC extension. Based on my experience with MSVC, it will use an aligned buffer to access the individual elements. This has a very heavy penalty because of partial-word access.

Instead of .m128i_u8, use _mm_extract_epi32(). This is in SSE4.1. But you're already relying with SSE4.1 with _mm_cvtepu8_epi32().

This situation is particularly bad since you're working with 1-byte granularity. If you were working with 2-byte (16-bit integer) granularity instead, there is an efficient solution using shuffle intrinsics.




回答2:


A combination of _mm_shuffle_epi8 and _mm_cvtsi128_si32 is what you need:

static const __m128i shuffleMask = _mm_setr_epi8(0,  4,  8, 12, -1, -1, -1, -1,
                                               -1, -1, -1, -1, -1, -1, -1, -1);
UINT color = _mm_cvtsi128_si32(_mm_shuffle_epi8(iClr, shuffleMask));


来源:https://stackoverflow.com/questions/8598942/how-do-i-convert-m128i-to-an-unsigned-int-with-sse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!