หมายเลขที่ไม่ได้ลงนามซึ่งแสดงเป็นสตรีมของบิตเขียนในรูปแบบไบนารี
รูปแบบไบนารีของ 54 คือ 110110
การบวกตัวเลขสองตัวโดยใช้บิต เราจะเพิ่มรูปแบบเลขฐานสองโดยใช้ตรรกะการบวกเลขฐานสอง
กฎสำหรับการบวกบิตคือ −
- 0+0 =0
- 1+0 =1
- 0+1 =1
- 1+1 =0 พร้อมพกพา =1
มาดูตัวอย่างการบวกตัวเลขสองตัวกัน
Input: a = 21 (10101) , b = 27 (11011) Output: 48 (110000)
คำอธิบาย − 10101 + 11011 =110000 เราจะเพิ่มบิตที่เริ่มต้นบิตที่มีนัยสำคัญน้อยที่สุด แล้วขยายพันธุ์ไปบิทถัดไป
ตัวอย่าง
#include <bits/stdc++.h>
#define M 32
using namespace std;
int binAdd (bitset < M > atemp, bitset < M > btemp){
bitset < M > 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{
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 < M > num1 (a);
bitset < M > num2 (b);
cout << binAdd (num1, num2) << endl;
} ผลลัพธ์
The sum of 678 and 436 is 1114