Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด BitConverter.ToSingle() ใน C# พร้อมตัวอย่าง


เมธอด BitConverter.ToSingle() ใน C# ใช้สำหรับแปลง 4 ไบต์ ในอาร์เรย์ไบต์ ให้เป็นค่าทศนิยมความแม่นยำเดี่ยว (float) เริ่มจากตำแหน่งที่ระบุ

ไวยากรณ์ (Syntax)

public static float ToSingle (byte[] value, int startIndex);
  • value — อาร์เรย์ไบต์ที่มีข้อมูล
  • startIndex — ดัชนีเริ่มต้น (0-based) ที่จะเริ่มอ่าน 4 ไบต์

ตัวอย่างที่ 1: อาร์เรย์ไบต์ขนาดเล็ก

using System;

public class Demo
{
    public static void Main()
    {
        byte[] arr = { 0, 1, 2, 3, 5, 7, 10 };

        Console.WriteLine("Byte Array = " + BitConverter.ToString(arr));

        for (int i = 0; i < arr.Length - 3; i += 4)
        {
            float res = BitConverter.ToSingle(arr, i);
            Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
            Console.WriteLine("Result = " + res);
        }
    }
}

ผลลัพธ์

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

ตัวอย่างที่ 2: อาร์เรย์ไบต์ขนาดใหญ่กว่า

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 = " + BitConverter.ToString(arr));

        for (int i = 0; i < arr.Length - 3; i += 4)
        {
            float res = BitConverter.ToSingle(arr, i);
            Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
            Console.WriteLine("Result = " + res);
        }
    }
}

ผลลัพธ์

Byte Array = 00-0A-02-05-20-2D-00-00-09-14-1E-32-4C-58
Value at index 0 = 0
Result = 6.114407E-36
Value at index 4 = 32
Result = 1.61878E-41
Value at index 8 = 9
Result = 9.201366E-09

ข้อสังเกตและแก้ไขจากตัวอย่างต้นฉบับ

  • เงื่อนไขลูปต้นฉบับ i < arr.Length - 4 ควรเป็น i < arr.Length - 3 หรือ i <= arr.Length - 4 เพื่อให้อ่านชุดสุดท้ายได้ครบ 4 ไบต์
  • ได้แก้ไขโค้ดตัวอย่างให้ถูกต้องแล้ว
  • BitConverter.ToString(arr) ใช้แสดงอาร์เรย์ไบต์ในรูปแบบ hex-string (เช่น 00-01-02-03)
  • ลำดับไบต์ (Endianness) ขึ้นอยู่กับแพลตฟอร์ม — ใช้ BitConverter.IsLittleEndian ตรวจสอบได้
  • หากต้องการควบคุม Endianness เอง ให้ใช้ BinaryPrimitives (.NET Core 2.1+) หรือเขียนฟังก์ชันแปลงเอง