
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add two unsigned numbers using bits in C++.
An unsigned number represented as a stream of bits is written in binary form.
The binary form of 54 is 110110.
Adding two numbers using bits, we will add their binary form using the binary addition logic.
Rules for bit addition is −
- 0+0 = 0
- 1+0 = 1
- 0+1 = 1
- 1+1 = 0 with carry = 1
Lets take an example to add two numbers,
Input: a = 21 (10101) , b = 27 (11011) Output: 48 (110000)
Explanation − 10101 + 11011 = 110000. We will add bits starting the least significant bit. And then propagating to the next bit.
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; }
Output
The sum of 678 and 436 is 1114
- Related Questions & Answers
- Add two numbers using ++ operator in C++.
- Add Two Numbers II in C++
- C++ Program to Add Two Numbers
- Write a program to add two complex numbers using C
- Add Two Numbers in Python
- Add two numbers represented by two arrays in C Program
- Program to Add Two Complex Numbers in C
- 8085 Program to Multiply two 8 bits numbers
- Unsigned and Signed Binary Numbers
- Alternate bits of two numbers to create a new number in C++
- 8085 Program to Add N numbers, of size 8 bits
- Java Program to Add Two Numbers
- Python program to add two numbers
- Maximize a given unsigned number by swapping bits at its extreme positions in C++
- 8085 Program to Multiply two numbers of size 8 bits
Advertisements