使用C ++中的位加两个无符号数字。

表示为比特流的无符号数字以二进制形式写入。

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