ในบทความนี้เราจะดูวิธีบวกเลขสองจำนวนโดยไม่ใช้ arithmetic operators เช่น +, ++, -, --
แก้ปัญหานี้ด้วย binary adder logic ใช้ half adder และ full adder บวกเลข binary 1 bit โดย cascade multiple adders ได้ circuit บวกเลขใหญ่กว่า
ใน adder ทำ XOR operation ระหว่างตัวเลข สำหรับ carry ทำ AND logic คุณสมบัติเหล่านี้ถูกนำมาใช้บวกเลขสองจำนวน
ตัวอย่างโค้ด
#include <iostream> using namespace std; int add(int a, int b) { while (b != 0) { //until there is no carry, iterater int carry = a & b; //find carry by anding a and b a = a ^ b; //perform XOR on a and b, and store into a b = carry << 1; //the carry is shifted one bit to the left, and store it to b } return a; } int main() { int a, b; cout << "Enter two numbers to add: "; cin >> a >> b; cout << "The result is: " << add(a, b); return 0; }ผลลัพธ์
Enter two numbers to add: 56 23 The result is: 79