2016-06-03 9 views
0

Jeder hat etwas gleichwertig (und hübscher als) den folgenden Code?Drehen von Paaren von Bytes in Floats

private static float[] PairsOfBytesToFloats(byte[] bytes) 
{ 
    if (bytes.Length.IsNotAMultipleOf(2)) throw new ArgumentException(); 

    float[] result = new float[bytes.Length/2]; 

    for (int i = 0; i < bytes.Length; i += 2) 
    { 
     result[i/2] = BitConverter.ToUInt16(bytes, i); 
    } 

    return result; 
} 
+0

'BitConverter.ToUInt16'? Vielleicht 'BitConverter.ToSingle'? – Dmitry

Antwort

0

Vielleicht ein bisschen von LINQ:

return Enumerable.Range(0, bytes.Length/2) 
    .Select(index => (float)BitConverter.ToUInt16(bytes, index*2)) 
    .ToArray(); 
0

Ich würde vorschlagen, dass Sie die Buffer.BlockCopy Methode anstelle der Schleife verwenden:

Buffer.BlockCopy(bytes, 0, result, 0, bytes.Length); 
Verwandte Themen