C# BitConverter.ToSingle()方法


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

更新於:04-12-2019

1K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.