Answer:
Code:
#include<bits/stdc++.h>
using namespace std;
char* prt_bin( int value, int length, char s[]){
for(int i=(length-1); i>=0; i--){
if((value>>i)&1) {
s[length-1-i] = '1';
// putchar('1');
}
else {
s[length-1-i] = '0';
// putchar('0');
}
}
s[length] = '\0';
return s;
}
int main(){
int nbits = 8, c, acc;
char s[nbits+1];
int multiplicand, multiplier, mq, mdr;
cout<<"Multiplicand: ";
cin>>multiplicand;
cout<<"Multiplier: ";
cin>>multiplier;
if(multiplier<0 || multiplier>255 ||multiplicand<0 || multiplicand>255){
cout<<"Given Multiplicand or multiplier is incorrect. Exiting the program.\\";
return 0;
}
c = 0; acc = 0;
cout<<"c and acc set to 0\\";
mq = multiplier;
mdr = multiplicand;
cout<<"mq set to multiplier = "<<multiplier<<" decimal and "<<prt_bin(multiplier, nbits, s)<<" binary\\";
cout<<"mdr set to multiplicand = "<<multiplicand<<" decimal and "<<prt_bin(multiplicand, nbits, s)<<" binary\\";
printf("---------------------------------------------------\\");
for(int i=1;i<=nbits;i++){
printf("step %d: %d %s ",i, c, prt_bin(acc, nbits, s));
printf("%s\\",prt_bin(mq, nbits, s));
char lsb = s[nbits-1];
if(lsb=='1'){
printf(" + %c %s ^add based on lsb=%c\\", c, prt_bin(mdr, nbits, s), lsb);
printf(" ----------\\");
acc = acc + multiplicand;
}
else{
printf(" + %c %s ^no add based on lsb=%c\\", c, prt_bin(0, nbits, s), lsb);
printf(" ----------\\");
}
printf(" %d %s ", c, prt_bin(acc, nbits, s));
printf("%s\\",prt_bin(mq, nbits, s));
printf(" >> shift right\\");
mq = mq>>1;
if(acc%2==1){
mq = mq+128;
}
acc = acc>>1;
printf(" %d %s ", c, prt_bin(acc, nbits, s));
printf("%s\\",prt_bin(mq, nbits, s));
printf("---------------------------------------------------\\");
}
char sr[nbits*2+1];
printf("check: binary decimal\\");
printf(" %s %d\\", prt_bin(multiplicand, nbits, s), multiplicand);
printf(" x %s x %d\\", prt_bin(multiplier, nbits, s), multiplier);
printf(" ---------------- ------\\");
printf(" %s %d\\", prt_bin(multiplier*multiplicand, nbits*2, sr), multiplier*multiplicand);
return 0;
}