将原始字节数据转换为float []

编程入门 行业动态 更新时间:2024-10-26 18:16:46
本文介绍了将原始字节数据转换为float []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这段代码可以将 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 []

本文发布于:2023-10-24 09:24:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字节   原始   数据   float

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!