C#中的BitConverter.ToSingle()方法用于返回一个单精度浮点数,该浮点数是从字节数组中指定位置的四个字节转换而来的。
语法如下-
public static float ToSingle (byte[] value, int begnIndex);
在上面,val是字节数组,而begnIndex是val中的开始位置。
现在让我们看一个例子-
using System; public class Demo { public static void Main() { byte[] arr = {0, 1, 2, 3, 5, 7, 10}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 0; i < arr.Length - 4; i = i + 4) { float res = BitConverter.ToSingle(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+res); } } }
输出结果
这将产生以下输出-
Byte Array = 00-01-02-03-05-07-0A Value = 0 Result = 3.820471E-37
现在让我们来看另一个示例-
using System; public class Demo { public static void Main() { byte[] arr = {0, 10, 2, 5, 32, 45, 0, 0, 9, 20, 30, 50, 76, 88}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 0; i < arr.Length - 4; i = i + 4) { float res = BitConverter.ToSingle(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+res); } } }
输出结果
这将产生以下输出-
Byte Array = 00-0A-02-05-20-2D-00-00-09-14-1E-32-4C-58 Value = 0 Result = 6.114407E-36 Value = 32 Result = 1.61878E-41 Value = 9 Result = 9.201366E-09