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

Chuyển Double thành Int64 (reinterpret bits) trong C#

Mục đích

Phương thức BitConverter.DoubleToInt64Bits(double value) trả về biểu diễn bit 64-bit (Int64) của số thực double theo chuẩn IEEE 754. Đây là **reinterpret**, không phải chuyển đổi giá trị.

Ví dụ 1

using System;

public class Demo
{
    public static void Main()
    {
        double d = 5.646587687;
        Console.WriteLine($"Double: {d}");

        long res = BitConverter.DoubleToInt64Bits(d);
        Console.WriteLine($"Int64 bits: {res}");
        Console.WriteLine($"Hex: 0x{res:X16}");
    }
}

Kết quả

Double: 5.646587687
Int64 bits: 4618043510978159912
Hex: 0x40175F9A3B8E3E28

Ví dụ 2

using System;

public class Demo
{
    public static void Main()
    {
        double d = 0.001;
        Console.WriteLine($"Double: {d}");

        long res = BitConverter.DoubleToInt64Bits(d);
        Console.WriteLine($"Int64 bits: {res}");
        Console.WriteLine($"Hex: 0x{res:X16}");
    }
}

Kết quả

Double: 0.001
Int64 bits: 4562254508917369340
Hex: 0x3F50624DD2F1A9FC

Ứng dụng

  • So sánh bit-level của double (ví dụ: kiểm tra -0.0 vs +0.0).
  • Serialization nhị phân tùy chỉnh.
  • Hash code cho double (tránh boxing).
  • Thao tác bit: kiểm tra NaN, Infinity, sign bit.

Ví dụ: Kiểm tra dấu âm

using System;

public class Demo
{
    public static void Main()
    {
        double[] values = { 1.0, -1.0, 0.0, -0.0, double.NaN, double.PositiveInfinity };

        foreach (double v in values)
        {
            long bits = BitConverter.DoubleToInt64Bits(v);
            bool isNegative = (bits & 0x8000000000000000L) != 0;
            Console.WriteLine($"{v,15} -> bits: 0x{bits:X16} -> Negative: {isNegative}");
        }
    }
}

Lưu ý

  • Ngược lại: BitConverter.Int64BitsToDouble(long).
  • Kết quả phụ thuộc endianness (BitConverter.IsLittleEndian).
  • Không dùng cho chuyển đổi số học (dùng Convert.ToInt64 hoặc cast).