Reputation: 357
Fast copy of Color32[] array to byte[] array
I already saw, quiet similar question.
But I want to convert the color[] array to byte[]
private byte[] color2ByteArray(Color[] colors)
{
int len = colors.Length;
byte[] result = new byte[len * 3];
int index = 0;
for (int i = 0; i < len; i++)
{
result[index++] = (byte)(colors[i].r * 255);
result[index++] = (byte)(colors[i].g * 255);
result[index++] = (byte)(colors[i].b * 255);
}
return result;
}
To obtain a proper color value and convert the byte[] array. I have to multiply the color x 255.
I've seen a lot of posts about Marshal.copy
But I don't know how to change it to make it faster
Upvotes: 1
Views: 1375
Reputation: 1062570
You're still going to have to do the math here. There are a few things that might help, though:
len
for the for
loop, but use colors.Length
directly - on some JITs/AOTs, this helps it elide the loop bounds checks (for(int i = 0 ; i < someArray.Length ; i++)
is recognized as a safe array walk)var color = colors[i]
or even ref Color color = ref colors[i]
in recent C#Vector
cast, allowing you to perform a vectorized multiply; i.e. var vec = 255 * (Vector4)colors[i];
, then just cast the 3 values from Vector4
as you fetch themAdditionally, if speed is important, I would avoid allocating an array in here; options:
IDisposable
that represents the lease segment (I can go into more detail if needed)Upvotes: 2