Home > Backend Development > C++ > body text

Add two unsigned numbers using bitwise operations in C++

WBOY
Release: 2023-08-27 17:53:06
forward
1109 people have browsed it

Add two unsigned numbers using bitwise operations in C++

An unsigned number represented as a bit stream written in binary form. The binary form of

54 is 110110.

To add two numbers using bits, we will add them in binary form using binary addition logic. The rule for

bit addition is -

  • 0 0 = 0
  • 1 0 = 1
  • 0 1 = 1
  • 1 1 = 0, carry = 1

Let’s take an example, add two numbers,

Input: a = 21 (10101) , b = 27 (11011)
Output: 48 (110000)
Copy after login

Explanation - 10101 11011 = 110000. We will add bits starting from the least significant bit. Then spread to the next person.

Example

#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;
}
Copy after login

Output

The sum of 678 and 436 is 1114
Copy after login

The above is the detailed content of Add two unsigned numbers using bitwise operations in C++. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template