C# BitConverter.ToSingle() Method


The BitConverter.ToSingle() method in C# is used to return a single-precision floating point number converted from four bytes at a specified position in a byte array.

Syntax

The syntax is as follows −

public static float ToSingle (byte[] value, int begnIndex);

Above, val is the byte array, whereas begnIndex is the beginning position within val.

Example

Let us now see an example −

 Live Demo

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);
      }
   }
}

Output

This will produce the following output −

Byte Array = 00-01-02-03-05-07-0A
Value = 0
Result = 3.820471E-37

Example

Let us now see another example −

 Live Demo

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);
      }
   }
}

Output

This will produce the following output −

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
raja
Published on 04-Dec-2019 11:29:41
Advertisements