Subtraction of two binary numbers using C
Basic Theory
Subtraction can be regarded as addition. For example A – B is same as A + (-B). In binary most computer uses 2’s complement form to represent negative binary number. The subtrahend is first converted to 2’s complement form to make it negative and then is added to minued. This is same as above example.
Loading…
Code Assumption
This code is capable to perform subtraction between two decimal numbers from 0 to 127. The subtrahend is first converted into 2’s complement form and then addition is performed. After addition the result is obtained. If the result has 1 in its MSB then it is treated as negative result and is converted to decimal format otherwise it is treated as positive number and converted to positive decimal.
Source Code:
#include#include void decimalToBinary(int, int [], int); int addBinary(int a1[], int a2[], int result[]){ int i, c = 0; for(i = 0; i 0); if(isSubtrahend) twoComplement(aOp); } int binaryToDecimal(int array[]){ int sum = 0, i; for(i = 0; i =0; i--){ printf("%d ", array[i]); } printf("\n"); } int main(){ int op1, op2, diff; int aOp1[8] = {0,0,0,0,0,0,0,0}; int aOp2[8] = {0,0,0,0,0,0,0,0}; int aDiff[8] = {0,0,0,0,0,0,0,0}; printf("Enter Minued: "); scanf("%d", &op1); while(op1 127){ printf("Enter Minued: "); scanf("%d", &op1); } printf("Enter subtrahend: "); scanf("%d", &op2); while(op2 127){ printf("Enter subtrahend: "); scanf("%d", &op2); } decimalToBinary(op1, aOp1, 0); decimalToBinary(op2, aOp2, 1); printf("Binary Equivalent of %d is ",op1); showBinary(aOp1, 8); printf("2's Complement Equivalent of %d is ",op2); showBinary(aOp2, 8); addBinary(aOp1, aOp2, aDiff); printf("Diffenece in Binary: "); showBinary(aDiff, 8); diff = binaryToDecimal(aDiff); printf("Difference in Decimal: %d", diff); return 0; }
Loading…