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

แปลงเลขทศนิยม (float) เป็นเลขฐานสอง (Binary) ใน C#

ภาพรวม

บทความต้นฉบับมีโค้ดที่ไม่ถูกต้องสำหรับการแปลง float เป็น binary (ลูป while(n >= 1) ทำงานผิดสำหรับทศนิยม) นี่คือวิธีที่ถูกต้อง

วิธีที่ถูกต้อง: แปลงส่วนเต็มและส่วนทศนิยมแยกกัน


using System;

public class FloatToBinary {
    public static string Convert(float number, int fractionalBits = 16) {
        // จัดการเครื่องหมาย
        bool isNegative = number < 0;
        number = Math.Abs(number);

        // แยกส่วนเต็มและทศนิยม
        int integerPart = (int)number;
        float fractionalPart = number - integerPart;

        // แปลงส่วนเต็มเป็น binary
        string integerBinary = Convert.ToString(integerPart, 2);

        // แปลงส่วนทศนิยม
        string fractionalBinary = "";
        for (int i = 0; i < fractionalBits; i++) {
            fractionalPart *= 2;
            int bit = (int)fractionalPart;
            fractionalBinary += bit.ToString();
            fractionalPart -= bit;
            if (fractionalPart == 0) break;
        }

        string result = integerBinary + (fractionalBinary.Length > 0 ? "." + fractionalBinary : "");
        return isNegative ? "-" + result : result;
    }

    public static void Main() {
        float f = 50.5f;
        Console.WriteLine($"{f} in binary = {Convert(f)}"); // 110010.1
    }
}

ผลลัพธ์


50.5 in binary = 110010.1

คำอธิบาย

  • 50 ในฐานสอง = 110010 (32+16+2)
  • 0.5 ในฐานสอง = 0.1 (1/2)
  • รวม = 110010.1

วิธีอื่น: IEEE 754 Single Precision (32-bit)


using System;

float f = 50.5f;
int bits = BitConverter.SingleToInt32Bits(f);
string ieee754 = Convert.ToString(bits, 2).PadLeft(32, '0');
Console.WriteLine($"IEEE 754: {ieee754}");
// Output: 01000010010010100000000000000000
// Sign(0) Exponent(10000100) Mantissa(10010100000000000000000)

หมายเหตุ

  • โค้ดต้นฉบับมีข้อบกพร่อง: ลูป while (n >= 1) และ n % 2 ไม่ทำงานถูกต้องกับ float
  • การแปลงทศนิยมเป็น binary อาจเป็น repeating binary (เช่น 0.1 decimal = 0.0001100110011... binary)
  • ใช้ BitConverter สำหรับ IEEE 754 representation