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

เมธอด BitConverter.ToDouble() ใน C# : แปลง 8 ไบต์เป็น Double

เมธอด BitConverter.ToDouble() ใน C# ใช้แปลง 8 ไบต์ (bytes) ในอาร์เรย์ไบต์ เริ่มจากตำแหน่งที่ระบุ ให้เป็นจำนวนทศนิยม double-precision (Double) ตามมาตรฐาน IEEE 754

รูปแบบไวยากรณ์ (Syntax)

public static double ToDouble(byte[] value, int startIndex);
  • value : อาร์เรย์ไบต์ต้นทาง
  • startIndex : ตำแหน่งเริ่มต้นในอาร์เรย์ ต้องมีพื้นที่อย่างน้อย 8 ไบต์จากตำแหน่งนี้
  • คืนค่า : Double ที่แปลงจาก 8 ไบต์

ตัวอย่างที่ 1: แปลงจากอาร์เรย์ไบต์ขนาดใหญ่

using System;

public class Demo
{
    public static void Main()
    {
        byte[] arr = { 0, 2, 5, 10, 20, 26, 34, 42, 50, 58, 66, 74, 82, 89, 97, 107, 115 };
        
        Console.WriteLine("Byte Array = {0}", BitConverter.ToString(arr));
        
        // อ่านทุก 8 ไบต์ เริ่มจาก index 1
        for (int i = 1; i < arr.Length - 7; i = i + 8)
        {
            double values = BitConverter.ToDouble(arr, i);
            Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
            Console.WriteLine("Result = " + values);
        }
    }
}

ผลลัพธ์

Byte Array = 00-02-05-0A-14-1A-22-2A-32-3A-42-4A-52-59-61-6B-73
Value at index 1 = 2
Result = 4.84667324189914E-67
Value at index 9 = 58
Result = 9.57203245252997E+247

ตัวอย่างที่ 2: อาร์เรย์สั้น มีแค่กลุ่มเดียว

using System;

public class Demo
{
    public static void Main()
    {
        byte[] arr = { 0, 3, 7, 10, 18, 20, 25, 26, 34 };
        
        Console.WriteLine("Byte Array = {0}", BitConverter.ToString(arr));
        
        for (int i = 1; i < arr.Length - 7; i = i + 8)
        {
            double values = BitConverter.ToDouble(arr, i);
            Console.WriteLine("\nValue at index " + i + " = " + arr[i]);
            Console.WriteLine("Result = " + values);
        }
    }
}

ผลลัพธ์

Byte Array = 00-03-07-0A-12-14-19-1A-22
Value at index 1 = 3
Result = 2.09001158167895E-144

ข้อสังเกตสำคัญ

  • ใช้ Little-endian (byte น้ำหนักน้อยอยู่ index ต่ำ) ตามแพลตฟอร์ม x86/x64
  • ตรวจสอบ BitConverter.IsLittleEndian ก่อนใช้งานข้ามแพลตฟอร์ม
  • 8 ไบต์ = 64 bits = 1 bit sign + 11 bits exponent + 52 bits mantissa (IEEE 754 double)
  • ค่าที่ได้อาจเป็น denormalized, infinity, NaN ขึ้นอยู่กับ bit pattern

เมธอดคู่ควร: Double → Byte[]

double d = 3.14159;
byte[] bytes = BitConverter.GetBytes(d);
// bytes จะมี 8 elements

// แปลงกลับ
double restored = BitConverter.ToDouble(bytes, 0);
// restored == 3.14159

สรุป

  • ใช้สำหรับ deserialize binary data, network protocols, file I/O
  • ต้องมี byte array อย่างน้อย 8 bytes จาก startIndex
  • คู่กับ BitConverter.GetBytes(double) สำหรับการแปลงสองทาง
  • สำหรับ float (4 bytes) ใช้ BitConverter.ToSingle()