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

โปรแกรม C++ บวกตัวเลขไม่มีเครื่องหมาย (Unsigned) ด้วยบิต (Bitwise Addition)

การบวกแบบบิต (Bitwise Addition)

ตัวเลขในรูปแบบไบนารี (bits) สามารถบวกกันได้โดยใช้ตรรกะการบวกบิต:

  • 0 + 0 = 0
  • 1 + 0 = 1
  • 0 + 1 = 1
  • 1 + 1 = 0 พร้อม carry = 1

ตัวอย่าง

a = 21 (10101), b = 27 (11011)
10101 + 11011 = 110000 (48)

อัลกอริทึม

  1. แปลงตัวเลขทั้งสองเป็น bitset ขนาด 32 บิต
  2. วนลูปทีละบิตตั้งแต่ LSB (บิตน้อยที่สุด)
  3. คำนวณผลบวกและ carry ตามกฎข้างต้น
  4. เก็บผลลัพธ์ใน bitset ผลลัพธ์
  5. แปลงกลับเป็น unsigned long

โค้ดภาษา C++

#include <bits/stdc++.h>
#define M 32
using namespace std;

int binAdd(bitset atemp, bitset btemp) {
    bitset ctemp;
    for (int i = 0; i < M; i++) ctemp[i] = 0;
    
    int carry = 0;
    for (int i = 0; i < M; i++) {
        if (atemp[i] + btemp[i] == 0) {
            if (carry == 0) ctemp[i] = 0;
            else { ctemp[i] = 1; carry = 0; }
        }
        else if (atemp[i] + btemp[i] == 1) {
            if (carry == 0) ctemp[i] = 1;
            else ctemp[i] = 0;
        }
        else { // 1+1 = 2
            if (carry == 0) { ctemp[i] = 0; carry = 1; }
            else ctemp[i] = 1;
        }
    }
    return ctemp.to_ulong();
}

int main() {
    int a = 678, b = 436;
    cout << "The sum of " << a << " and " << b << " is ";
    bitset num1(a);
    bitset num2(b);
    cout << binAdd(num1, num2) << endl;
    return 0;
}

ผลลัพธ์

The sum of 678 and 436 is 1114