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

การแปลงจำนวนจุดลอยตัวความแม่นยำสองเท่าที่ระบุเป็นจำนวนเต็มมีเครื่องหมาย 64 บิตใน C#

ภาพรวม

เมธอด BitConverter.DoubleToInt64Bits(Double) นำรูปแบบบิตของ double มาตีความเป็น long (Int64) โดยไม่เปลี่ยนค่าตัวเลข

ตัวอย่าง 1: ค่าทศนิยมทั่วไป

using System;

public class Demo {
    public static void Main() {
        double d = 5.646587687;
        Console.Write("Value = " + d);
        long res = BitConverter.DoubleToInt64Bits(d);
        Console.Write("\n64-bit signed integer = " + res);
    }
}

ผลลัพธ์ตัวอย่าง 1

Value = 5.646587687
64-bit signed integer = 4618043510978159912

ตัวอย่าง 2: ค่าทศนิยมเล็ก

using System;

public class Demo {
    public static void Main() {
        double d = 0.001;
        Console.Write("Value = " + d);
        long res = BitConverter.DoubleToInt64Bits(d);
        Console.Write("\n64-bit signed integer = " + res);
    }
}

ผลลัพธ์ตัวอย่าง 2

Value = 0.001
64-bit signed integer = 4562254508917369340

สรุป

  • เป็นการ คัดลอกบิต (bitwise copy) ไม่ใช่การแปลงค่าตัวเลข
  • ใช้ในงานระดับต่ำ เช่น การส่งข้อมูลผ่านเครือข่าย การเขียนไฟล์ไบนารี
  • คู่กับ Int64BitsToDouble สำหรับการทำงานย้อนกลับ