logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jul19/bitSubtraction.c

/*

Demonstrating subtraction using only binary operators

Subtraction is the same as adding a negative number,

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;

	x = atoi(argv[1]); //getting first addend
	y = atoi(argv[2]); //getting second addend

	//y = ~y+1; not a binary operator

	y = add(~y, 1);

	sum = add(x, y);


	printf("difference = %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;

}