|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jul19/bitAddition.c
/*
Demonstrating addition using only binary operators
This is how the CPU would add two numbers together.
*/
#include <stdio.h>
#include <stdlib.h>
int add(int x, int y);
int main(int argc, char *argv[]){
//prints usage statement if user doesn't enter two numbers
if(argc != 3){
fprintf(stderr, "Usage: %s <number> <number>\n", argv[0]);
exit(1);
}
int x, y, sum, carry;
x = atoi(argv[1]); //getting first addend
y = atoi(argv[2]); //getting second addend
sum = add(x, y);
//initializing the sum and carry
printf("sum = %d\n", sum); //print the sum
return 0;
}
int add(int x, int y){
int sum, carry;
sum = x ^ y; // x XOR y
carry = x & y; // x AND y
while(carry != 0){ //loop while carry is not 0
carry = carry << 1; //left shift carry by 1
x = sum; //initialize x as sum
y = carry; //initialize y as the carry
sum = x ^ y; //calculate the sum
carry = x & y; // calculate the carry
//if carry is not zero, continue looping
}
return sum;
}
|