Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Diễn giải lại Int64 thành Double (reinterpret bits) trong C#

Mục đích

Phương thức BitConverter.Int64BitsToDouble(long value) **diễn giải lại** (reinterpret) 64 bit của số nguyên có dấu (Int64) thành số thực double (IEEE 754), **không phải chuyển đổi giá trị số học**.

Ví dụ 1

using System;

public class Demo
{
    public static void Main()
    {
        long d = 9846587687;
        Console.WriteLine($"Int64: {d}");

        double res = BitConverter.Int64BitsToDouble(d);
        Console.WriteLine($"Double (reinterpret): {res}");
    }
}

Kết quả

Int64: 9846587687
Double (reinterpret): 4.86486070491012E-314

Ví dụ 2

using System;

public class Demo
{
    public static void Main()
    {
        long d = 20;
        Console.WriteLine($"Int64: {d}");

        double res = BitConverter.Int64BitsToDouble(d);
        Console.WriteLine($"Double (reinterpret): {res}");
    }
}

Kết quả

Int64: 20
Double (reinterpret): 9.88131291682493E-323

Giải thích kỹ thuật

  • Double (IEEE 754) dùng 64 bit: 1 bit dấu, 11 bit exponent, 52 bit mantissa.
  • Int64BitsToDouble copy nguyên bản bit pattern từ long sang double.
  • Kết quả thường là số cực nhỏ (denormalized) hoặc NaN/Infinity tùy bit pattern.
  • Ngược lại: BitConverter.DoubleToInt64Bits(double).

Khi nào dùng?

  • Xử lý dữ liệu nhị phân cấp thấp (network protocol, file format).
  • Serialization tùy chỉnh, bit manipulation.
  • **Không dùng** cho chuyển đổi số học thông thường (dùng Convert.ToDouble hoặc cast).

Lưu ý

  • Phương thức này là `static` và `unsafe` bên trong (con trỏ).
  • Kết quả phụ thuộc vào endianness của hệ thống (BitConverter.IsLittleEndian).