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

คูณเลขฐานสอง (Binary Multiplication) ใน C#

ภาพรวม

คูณเลขฐานสองโดยจัดการเป็นตัวเลข decimal ที่ประกอบด้วย 0 และ 1 ใช้หลักการคูณแบบ Manual (shift and add)

โค้ดตัวอย่าง


using System;

class Demo {
    public static void Main() {
        long val1 = 11100; // binary as decimal
        long val2 = 10001;

        Console.WriteLine($"Binary one: {val1}");
        Console.WriteLine($"Binary two: {val2}");

        long prod = MultiplyBinary(val1, val2);
        Console.WriteLine($"Product = {prod}");
    }

    static long MultiplyBinary(long val1, long val2) {
        long prod = 0;
        long factor = 1;

        while (val2 != 0) {
            long digit = val2 % 10;
            if (digit == 1) {
                prod = AddBinary(prod, val1 * factor);
            }
            val2 /= 10;
            factor *= 10;
        }
        return prod;
    }

    static long AddBinary(long val1, long val2) {
        long i = 0, rem = 0, res = 0;
        long[] sum = new long[64];

        while (val1 != 0 || val2 != 0) {
            sum[i++] = (val1 % 10 + val2 % 10 + rem) % 2;
            rem = (val1 % 10 + val2 % 10 + rem) / 2;
            val1 /= 10;
            val2 /= 10;
        }
        if (rem != 0) sum[i++] = rem;

        i--;
        while (i >= 0) res = res * 10 + sum[i--];
        return res;
    }
}

ผลลัพธ์


Binary one: 11100
Binary two: 10001
Product = 111011100

ตรวจสอบความถูกต้อง

  • 11100₂ = 28₁₀
  • 10001₂ = 17₁₀
  • 28 × 17 = 476₁₀
  • 111011100₂ = 256+128+64+16+8+4 = 476₁₀ ✓

วิธีที่แนะนำ (Standard)


using System;

string bin1 = "11100";
string bin2 = "10001";

int n1 = Convert.ToInt32(bin1, 2); // 28
int n2 = Convert.ToInt32(bin2, 2); // 17

int product = n1 * n2; // 476
string result = Convert.ToString(product, 2); // "111011100"

Console.WriteLine($"{bin1} × {bin2} = {result}");

สำหรับเลขใหญ่: BigInteger


using System.Numerics;

BigInteger MultiplyBinary(string bin1, string bin2) {
    BigInteger n1 = 0, n2 = 0;
    foreach (char c in bin1) n1 = n1 * 2 + (c - '0');
    foreach (char c in bin2) n2 = n2 * 2 + (c - '0');
    return n1 * n2;
}

string ToBinaryString(BigInteger n) {
    if (n == 0) return "0";
    string s = "";
    while (n > 0) {
        s = (n % 2) + s;
        n /= 2;
    }
    return s;
}

หลักการคูณฐานสอง (Shift and Add)

     11100  (28)
   × 10001  (17)
   -------
     11100  (28 × 1)
    00000   (28 × 0, shift 1)
   00000    (28 × 0, shift 2)
  00000     (28 × 0, shift 3)
 11100      (28 × 1, shift 4)
 -------
 111011100  (476)