我有这段代码可以将 byte [] 转换为 float [] 。
I have this code for converting a byte[] to float[].
public float[] ConvertByteToFloat(byte[] array) { float[] floatArr = new float[array.Length / sizeof(float)]; int index = 0; for (int i = 0; i < floatArr.Length; i++) { floatArr[i] = BitConverter.ToSingle(array, index); index += sizeof(float); } return floatArr; }问题是,我通常会得到 NaN 结果!为什么会这样呢?我检查了 byte [] 中是否有数据,并且数据似乎还不错。如果有帮助,则值的示例为:
Problem is, I usually get a NaN result! Why should this be? I checked if there is data in the byte[] and the data seems to be fine. If it helps, an example of the values are:
new byte[] { 231, 255, 235, 255, }但这转换为浮点型后,返回 NaN (不是数字)。可能是什么问题呢?还有其他更好的方法可以将 byte [] 转换为 float [] 吗?我确信读入缓冲区的值是正确的,因为我将其与其他程序(对.wav文件执行放大)进行了比较。
But this returns NaN (Not a Number) after conversion to float. What could be the problem? Are there other better ways of converting byte[] to float[]? I am sure that the values read into the buffer are correct since I compared it with my other program (which performs amplification for a .wav file).
推荐答案如果出现字节顺序问题,则应检查 BitConverter.IsLittleEndian 的值,以确定是否必须反转字节:
If endianness is the problem, you should check the value of BitConverter.IsLittleEndian to determine if the bytes have to be reversed:
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; }更多推荐
将原始字节数据转换为float []
发布评论