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

โปรแกรม Java แปลงทศนิยมเป็น Binary

ตัวอย่าง: แปลงจำนวนเต็มเป็น Binary

public class Demo {
    static void decimalToBinary(int n) {
        if (n == 0) {
            System.out.print("0");
            return;
        }
        
        int[] binary = new int[32]; // int 32 bits
        int i = 0;
        while (n > 0) {
            binary[i++] = n % 2;
            n /= 2;
        }
        
        // พิมพ์ย้อนกลับ (MSB first)
        for (int j = i - 1; j >= 0; j--) {
            System.out.print(binary[j]);
        }
    }
    
    public static void main(String[] args) {
        int n = 89;
        System.out.print("Binary of " + n + " = ");
        decimalToBinary(n);
        System.out.println();
        
        // วิธีง่ายด้วย built-in
        System.out.println("Integer.toBinaryString(89) = " + Integer.toBinaryString(89));
    }
}

ผลลัพธ์

Binary of 89 = 1011001
Integer.toBinaryString(89) = 1011001

คำอธิบาย: หาร 2 ซ้ำๆ เก็บเศษ แล้วอ่านย้อนกลับ Built-in Integer.toBinaryString() ทำให้ง่ายกว่า

ขยาย: Floating Point (IEEE 754)

หัวข้อนี้มักหมายถึง จำนวนเต็ม (decimal integer → binary)
ถ้าต้องการแปลง float/double เป็น binary representation (IEEE 754):

float f = 3.14f;
int bits = Float.floatToIntBits(f);
System.out.println("IEEE 754 binary: " + Integer.toBinaryString(bits));
// 32 bits: sign(1) | exponent(8) | mantissa(23)

double d = 3.14;
long bits = Double.doubleToLongBits(d);
System.out.println("IEEE 754 binary: " + Long.toBinaryString(bits));
// 64 bits: sign(1) | exponent(11) | mantissa(52)