I don't if I am doing it right, but I am using this method to convert a byte array to float array as shown in this link :
public static float[] ConvertByteToFloat(byte[] array) {
float[] floatArr = new float[array.Length / 4];
for (int i = 0; i < floatArr.Length; i++) {
if (BitConverter.IsLittleEndian) {
Array.Reverse(array, i * 4, 4);
}
floatArr[i] = BitConverter.ToSingle(array, i * 4);
}
return floatArr;
}
the input array is an array containing wave raw data (with no header)
The problem is that i am getting (after conversion) values like :
-9.66012E+24, 1963.15576, -5.11384777E-36, -1.19718621E-07
How can I convert this array to a float array and its values should be between -1.0 and 1.0?
Edit:
my input array starts like this :
byte[] {
232,
255,
235,
255,
232,
255,
235,
255,
232,
255,
235,
255,
232,
255,
235,
255,
...
}
You can look at the implementation of WriteSample()
:
public void WriteSample(float sample)
{
if (WaveFormat.BitsPerSample == 16)
{
writer.Write((Int16)(Int16.MaxValue * sample));
dataChunkSize += 2;
}
...
Note how that it converts a float
to a 16-bit signed integer by multiplying it by Int16.MaxValue
. That's because the internal data format is signed 16-bit integers between -Int16.MaxValue and +Int16.MaxValue.
This means that the values you're working with are Int16
(aka short
), and you need to convert them back to floats by dividing them by Int16.MaxValue
.
For example, given your sample input:
byte[] bytes = { 232, 255, 235, 255, 232, 255, 235, 255, 232, 255, 235, 255, 232, 255, 235, 255 };
for (int i = 0; i < bytes.Length - 4; i += 4)
{
float f = BitConverter.ToInt16(bytes, i) / (float)Int16.MaxValue;
Console.WriteLine(f);
}