PROWAREtech
.NET: Convert Float Array to Byte Array
How to use the BitConverter class to convert an array of floats to an array of bytes and back again; written in C#.
In C#, convert an array of floats to an array of bytes and back again using the BitConverter
class, which provides methods for converting base data types to an array of bytes and vice versa. Here’s how to do it:
1. Converting an Array of Floats to an Array of Bytes
To convert an array of floats to an array of bytes, iterate over the float array and convert each float to bytes. Since each float
in C# is typically 4 bytes (32 bits), allocate an appropriate number of bytes to hold the converted values.
float[] floatArray = new float[] { 1.0f, 2.0f, 3.0f };
byte[] byteArray = new byte[floatArray.Length * sizeof(float)];
// NOTE: sizeof(float) is typically 4 (bytes)
for (int i = 0; i < floatArray.Length; i++)
{
BitConverter.GetBytes(floatArray[i]).CopyTo(byteArray, i * sizeof(float));
}
2. Converting an Array of Bytes Back to an Array of Floats
To convert the byte array back to a float array, read every 4 bytes from the byte array and convert them back into floats.
float[] convertedFloatArray = new float[byteArray.Length / sizeof(float)];
for (int i = 0; i < convertedFloatArray.Length; i++)
{
convertedFloatArray[i] = BitConverter.ToSingle(byteArray, i * sizeof(float));
}
Comment