Add two bit strings
Given two bit sequences as strings, write a function to return the addition of the two sequences. Bit strings can be of different lengths also. For example, if string 1 is “1100011″ and second string 2 is “10″, then the function should return “1100101″.
Since sizes of two strings may be different, we first make the size of smaller string equal to that of bigger string by adding leading 0s. After making sizes same, we one by one add bits from rightmost bit to leftmost bit. In every iteration, we need to sum 3 bits: 2 bits of 2 given strings and carry. The sum bit will be 1 if, either all of the 3 bits are set or one of them is set. So we can do XOR of all bits to find the sum bit. How to find carry – carry will be 1 if any of the two bits is set. So we can find carry by taking OR of all pairs. Following is step by step algorithm.
1. Make them equal sized by adding 0s at the begining of smaller string.
2. Perform bit addition
…..Boolean expression for adding 3 bits a, b, c
…..Sum = a XOR b XOR c
…..Carry = (a AND b) OR ( b AND c ) OR ( c AND a )
Following is C++ implementation of the above algorithm.
#include <iostream>
using namespace std;
//adds the two bit strings and return the result
string addBitStrings( string first, string second );
// Helper method: given two unequal sized bit strings, converts them to
// same length by aadding leading 0s in the smaller string. Returns the
// the new length
int makeEqualLength(string &str1, string &str2)
{
int len1 = str1.size();
int len2 = str2.size();
if (len1 < len2)
{
for (int i = 0 ; i < len2 - len1 ; i++)
str1 = '0' + str1;
return len2;
}
else if (len1 > len2)
{
for (int i = 0 ; i < len1 - len2 ; i++)
str2 = '0' + str2;
}
return len1; // If len1 >= len2
}
// The main function that adds two bit sequences and returns the addition
string addBitStrings( string first, string second )
{
string result; // To store the sum bits
// make the lengths same before adding
int length = makeEqualLength(first, second);
int carry = 0; // Initialize carry
// Add all bits one by one
for (int i = length-1 ; i >= 0 ; i--)
{
int firstBit = first.at(i) - '0';
int secondBit = second.at(i) - '0';
// boolean expression for sum of 3 bits
int sum = (firstBit ^ secondBit ^ carry)+'0';
result = (char)sum + result;
// boolean expression for 3-bit addition
carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry);
}
// if overflow, then add a leading 1
if (carry)
result = '1' + result;
return result;
}
// Driver program to test above functions
int main()
{
string str1 = "1100011";
string str2 = "10";
cout << "Sum is " << addBitStrings(str1, str2);
return 0;
}
Output:
Sum is 1100101
This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Here is a code without doing padding:
#include<stdio.h> #include<stdlib.h> #include<string.h> #define max(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) #define min(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) int get_length(char * str) { int length = 0; while(*str != '\0') { length++; str++; } return length; } char * add_bit_strings(char * a, char * b) { int a_len = get_length(a); int b_len = get_length(b); int first_bit; int second_bit; int carry_bit = 0; int sum; char * result; int i, j; char * long_string; char * short_string; if(a_len >= b_len) { long_string = a; short_string = b; } else { long_string = b; short_string = a; } int long_len = max(a_len, b_len); int short_len = min(a_len, b_len); result = (char *)malloc(sizeof(char)*long_len); for(i=long_len-1, j=short_len-1; i>=0; i--, j--) { first_bit = *(long_string+i)-'0'; if(j>=0) { second_bit = *(short_string+j)-'0'; } else { second_bit = 0; } sum = (first_bit ^ second_bit ^ carry_bit); if(sum == 0) { *(result+i) = '0'; } else { *(result+i) = '1'; } carry_bit = (first_bit & second_bit) | (second_bit & carry_bit) | (first_bit & carry_bit); } if (carry_bit) { char * overflow_result=(char *)malloc(sizeof(char)*long_len+1); strcat(overflow_result, "1"); strcat(overflow_result, result); return overflow_result; } return result; } int main(){ printf("Result=%s\n", add_bit_strings("01010101", "1011011001")); printf("Result=%s\n", add_bit_strings("", "1011011001")); printf("Result=%s\n", add_bit_strings("1111111111", "1011011001")); return 0; }Result=1100101110
Result=1011011001
Result=11011011000
There is a solution with iterator
string addBitStr(string str1, string str2) { string result; string::iterator it1 = str1.end() - 1, it2 = str2.end() - 1, it; int carry = 0; for(int i = min(str1.size(), str2.size()); i > 0; i--, it1--, it2--) { int bit1 = *it1 - '0', bit2 = *it2 - '0'; int sum = bit1 ^ bit2 ^ carry; carry = (bit1 & bit2) | (bit1 & carry) | (bit2 & carry); result = (char)(sum + '0') + result; } if(it1 + 1 == str1.begin()) it = it2; else it = it1; for(int i = abs(str1.size() - str2.size()); i > 0; i--, it--) { int bit = *it - '0'; int sum = bit ^ carry; carry = bit | carry; result = (char)(sum + '0') + result; } if(carry == 1) result = '1' + result; return result; }Sorry, there is a bug, the last 7th line should be:
carry = bit & carry;
#include <stdio.h> #include <stdlib.h> #include <string.h> char string1[] = "1100011"; char string2[] = "10"; char result[] = {'\n'}; int makeEqualLength(char *str1, char *str2) { int len1,len2,i; char *str_priv; len1 = strlen(str1); len2 = strlen(str2); if(len1 > len2) { /* Append Zero from array index Zero */ for(i = 0; i < (len1-len2); i++) str_priv[i] = '0'; memcpy(str_priv+i,str2,len2); memmove(str2,str_priv,len1); return len1; } else if(len2 > len1) { /* Append Zero from array index Zero */ for(i = 0; i < (len2-len1); i++) str_priv[i] = '0'; memcpy(str_priv+i,str1,len2); memmove(str2,str_priv,len1); str1 = str_priv; return len2; } } char * addString(char *first, char *second) { int firstBit, secondBit, i, sum, carry = 0; int length = makeEqualLength(first,second); for(i = length-1; i >= 0; i--) { firstBit = first[i] - '0'; secondBit = second[i] - '0'; sum = (firstBit ^ secondBit ^ carry); carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); result[i+1] = sum + '0'; } if(carry) result[0] = '1'; return result; } int main (int notused) { printf("Sum is %s\n",addString(string1,string2)); while(1); return 0; }@sagar Sethi
atoi function will convert bit string into decimal number, which is not what we want.
can't use carry = x/2;
no = (x+crarr)%2
???