Consider I have an SSE array with 16 bit data:
{1,2,3,4,5,6,7,8}
Now I need to convert this SSE array into 8 bit data by storing only the lower byte of 16 bit data in the first 8 bytes like:
{1,2,3,4,5,6,7,8,0,0,0,0,0,0,0,0}.
Is there any SSE instruction to perform this operation?
As @harold says in the comments above, you can do this quite easily with pshufb
aka _mm_shuffle_epi8
, e.g.
#include <stdio.h>
#include <tmmintrin.h>
static __m128i pack_16_to_8(const __m128i v)
{
const __m128i vperm = _mm_setr_epi8(0, 2, 4, 6, 8, 10, 12, 14, -1, -1, -1, -1, -1, -1, -1, -1);
return _mm_shuffle_epi8(v, vperm);
}
int main(void)
{
const __m128i v = _mm_setr_epi16(1, 2, 3, 4, 5, 6, 7, 8);
printf("%vhd -> %vd\n", v, pack_16_to_8(v));
return 0;
}
Compile and run:
$ gcc -Wall -mssse3 pack_16_to_8.c && ./a.out
1 2 3 4 5 6 7 8 -> 1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0
Addition to answer of Paul К:
SSE2 extension contains commands PACKSSWB(_mm_packs_epi16) and PACKUSWB (_mm_packus_epi16). These commands specially designed to convert 16-bit vector to 8-bit vector. They perform saturation of 16-bit (signed and unsigned) values if these values exceed range 8-bit unsigned integer (0..255).
#include <iostream>
#include <emmintrin.h>
template<class T> inline void Print(const __m128i & v)
{
T b[sizeof(v) / sizeof(T)];
_mm_storeu_si128((__m128i*)b, v);
for (int i = 0; i < sizeof(v) / sizeof(T); i++)
std::cout << int(b[i]) << " ";
std::cout << std::endl;
}
int main()
{
__m128i v16 = _mm_setr_epi16(1, 2, 3, 4, 5, 6, 7, 8);
Print<uint8_t>(_mm_packs_epi16(v16, _mm_setzero_si128()));
Print<uint8_t>(_mm_packus_epi16(v16, _mm_setzero_si128()));
return 0;
}
Output:
1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0