首页 > 文章列表 > 使用C++中的位运算,将两个无符号数相加

使用C++中的位运算,将两个无符号数相加

c语言 位运算 无符号数相加
322 2023-09-04

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

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