/* A program to add two 4-bit unsigned binary numbers * NOTE: Result is a 5-bit number * * Programmed by: Fran Jarnjak * 1/29/2003 */ #include // Function that adds parameter 'first' and parameter 'second' // while taking into the account possible carry. // All the parameters are in binary - either 1 or 0 // Parameter that holds carry should be passed by address (reference) // Return value of the function is either 1 or 0 which is the result of the addition and // carry parameter is updated as well to hold correct value. int binaryAdd(int first, int second, int * carry) { int result; // exhaust all of the possible cases as described in the handout if(first==0 && second==0) { result = (*carry); *carry = 0; } else if(first==0 && second==1) { if(*carry==0) result = 1; else { result = 0; *carry = 1; } } else if(first==1 && second==0) { if(*carry==0) { result = 1; } else { result = 0; *carry = 1; } } else if(first==1 && second==1) { if(*carry==0) { result = 0; *carry = 1; } else { result = 1; *carry = 1; } } return result; } int main(void) { int i; // loop counter int carry=0; // Initialize carry to 0 (IMPORTANT) // MSB - Most significant bit (leftmost) // LSB - Least significant bit (rightmost) int num1[4]; // MSB - index 0 LSB index 3 int num2[4]; // MSB - index 0 LSB index 3 int result[5]; // MSB - index 0 LSB index 4 char e_result[6]; // 5+null char char e_num1[5]; // 4+null char char e_num2[5]; // 4+null char // get data cout << "Enter first number: "; cin >> e_num1; cout << "Enter second number: "; cin >> e_num2; // convert from char array to int array // It is useful to have data in int array when doing conversion into decimal // value of a certain binary number which is not implemented in this program. for(i=0;i<4;i++) { // NOTE: No checking that the actual number entered is indeed // a binary number // // ASCII value of '0' = 48 // ASCII value of '1' = 49 num1[i] = e_num1[i]-48; num2[i] = e_num2[i]-48; } // initialize result array for(i=0;i<5;i++) result[i] = 0; // do the addition for(i=3;i>=0;i--) { // go from right to left (LSB to MSB) result[i+1] = binaryAdd(num1[i],num2[i],&carry); // needs to add 1 to the counter // since LSB index for result // is 1 more than LSB of operands e_result[i+1] = result[i+1]+48; // For display purposes - convert to char array } result[0] = carry; // Add MSB of result e_result[0] = result[0] + 48; e_result[5] = '\0'; // Put NULL Char // print out the results cout << " " << e_num1 << endl; cout << " +" << e_num2 << endl; cout << " -----" << endl; cout << " " << e_result << endl << endl; return 0; // since main() has a return type int; for UNIX compiler compatibility }