Ich weiß, das ist eine alte Frage, aber da niemand eine Lösung mit der IEEE Float-Darstellung gab, hier ist eine.
// Use three unions instead of one to avoid pipeline stalls
union { float f; uint32_t i; } t, u, v, w;
t.f = 32768.0f;
float const b = 256.f/255.f;
for(int size = width * height; size > 0; --size)
{
u.i = t.i | bytepixel[0]; floatpixel[0] = (u.f - t.f) * b;
v.i = t.i | bytepixel[1]; floatpixel[1] = (v.f - t.f) * b;
w.i = t.i | bytepixel[2]; floatpixel[2] = (w.f - t.f) * b;
floatpixel[3] = 1.0f; // A
floatpixel += 4;
bytepixel += 4;
}
Das ist mehr als doppelt so schnell als int
zu float
Umwandlung auf meinem Computer (Core 2 Duo CPU).
Hier ist eine SSE3-Version des obigen Codes, der 16 Floats gleichzeitig ausführt. Es erfordert bytepixel
und floatpixel
zu 128-Bit ausgerichtet sein, und die Gesamtgröße zu einem Vielfachen von 4. Beachten Sie, dass die SSE3 integrierte Int Float Conversions wird hier nicht viel helfen, da sie sowieso eine zusätzliche Multiplikation erfordern. Ich glaube, das ist der kürzeste Weg, um Anweisungen zu bekommen, aber wenn Ihr Compiler nicht schlau genug ist, möchten Sie vielleicht die Dinge von Hand ausrollen und planen.
/* Magic values */
__m128i zero = _mm_set_epi32(0, 0, 0, 0);
__m128i magic1 = _mm_set_epi32(0xff000000, 0xff000000, 0xff000000, 0xff000000);
__m128i magic2 = _mm_set_epi32(0x47004700, 0x47004700, 0x47004700, 0x47004700);
__m128 magic3 = _mm_set_ps(32768.0f, 32768.0f, 32768.0f, 32768.0f);
__m128 magic4 = _mm_set_ps(256.0f/255.0f, 256.0f/255.0f, 256.0f/255.0f, 256.0f/255.0f);
for(int size = width * height/4; size > 0; --size)
{
/* Load bytes in vector and force alpha value to 255 so that
* the output will be 1.0f as expected. */
__m128i in = _mm_load_si128((__m128i *)bytepixel);
in = _mm_or_si128(in, magic1);
/* Shuffle bytes into four ints ORed with 32768.0f and cast
* to float (the cast is free). */
__m128i tmplo = _mm_unpacklo_epi8(in, zero);
__m128i tmphi = _mm_unpackhi_epi8(in, zero);
__m128 in1 = _mm_castsi128_ps(_mm_unpacklo_epi16(tmplo, magic2));
__m128 in2 = _mm_castsi128_ps(_mm_unpackhi_epi16(tmplo, magic2));
__m128 in3 = _mm_castsi128_ps(_mm_unpacklo_epi16(tmphi, magic2));
__m128 in4 = _mm_castsi128_ps(_mm_unpackhi_epi16(tmphi, magic2));
/* Subtract 32768.0f and multiply by 256.0f/255.0f */
__m128 out1 = _mm_mul_ps(_mm_sub_ps(in1, magic3), magic4);
__m128 out2 = _mm_mul_ps(_mm_sub_ps(in2, magic3), magic4);
__m128 out3 = _mm_mul_ps(_mm_sub_ps(in3, magic3), magic4);
__m128 out4 = _mm_mul_ps(_mm_sub_ps(in4, magic3), magic4);
/* Store 16 floats */
_mm_store_ps(floatpixel, out1);
_mm_store_ps(floatpixel + 4, out2);
_mm_store_ps(floatpixel + 8, out3);
_mm_store_ps(floatpixel + 12, out4);
floatpixel += 16;
bytepixel += 16;
}
bearbeiten: Verbesserung der Genauigkeit von (f + c/b) * b
statt f * b + c
verwenden.
Bearbeiten: SSE3-Version hinzufügen.
Nur der Vollständigkeit halber wird 128 im Byte-Puffer .5019607843f im Float-Puffer sein, nicht .5f. –