C# BitConverter.ToSingle() 方法

csharpserver side programmingprogramming更新于 2025/9/13 2:33:00

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("
Value = "+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("
Value = "+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

相关文章