Reputation: 53
I'm trying to add two binary numbers together using only logical statements and binary arithmetic operators. But I'm confused on how to actually change the bits. It is mostly the out variable that I am trying to change, but it keeps getting zeroed every time I print it.
#include <stdio.h>
void execute_add(int a, int b){
int i = 0;
int bit;
int bit2;
int carryOut = 0;
int out = 10;
int overflow = 0;
for(i = 0; i <32 ; i++){
bit = (a >> i) & 1;
bit2 = (b >> i) & 1;
if(bit==1 && bit2==1 && carryOut == 0){
carryOut = 1;
out = 0 | (0x1 >> i);
}else if(bit==1 && bit2==1 && carryOut == 1){
carryOut = 1;
out = 1 | (0x1 >> i);
}else if(bit==0 && bit2==0 && carryOut == 0){
carryOut = 0;
out= 0 | (0x1 >> i);
}else if(bit==0 && bit2==0 && carryOut == 1){
carryOut = 0;
out = 1 | (0x1 >> i);
}else if(bit==1 && bit2==0 && carryOut == 0){
carryOut = 0;
out = 1 | (0x1 >> i);
}else if(bit==1 && bit2==0 && carryOut == 1){
carryOut = 1;
out = 0 | (0x1 >> i);
}else if(bit==0 && bit2==1 && carryOut == 0){
carryOut = 0;
out = 1 | (0x1 >> i);
}else if(bit==0 && bit2==1 && carryOut == 1){
carryOut = 1;
out = 0 | (0x1 >> i);
}else{
}//if else
}//for loop
printf("\n");
bit = (a >> 31) & 1;
bit2 = (a >> 31)& 1;
int bit3 = (out >> 31) & 1;
if( bit == 1 && bit2== 1 && bit3 == 0){
overflow = 1;
}else if (bit == 0 && bit2 == 0 && bit3 == 1){
overflow = 1;
}else{
}//overflow check
int j;
int g = 0;
for(j = 31; j>=0; j--){
if(g%4==0 && g!=0){
printf(" ");
}
bit2 = (out >> j) & 1;
printf("%d", bit2);
g++;
}
printf("\n");
}
int main (){
int a = 34;
int b = 17;
execute_add(a, b);
return 0;
}
Upvotes: 1
Views: 469
Reputation: 12711
With each of these statements in your for loop:
out = 0 | x;
You're resetting out
, and clearing away all the work you've already done. You probably mean to do:
out = out | x
Or, equivalently,
out |= x
You also are right-shifting 1
all over the place, which is not what you're looking for; for any shift greater than zero, that's going to give you zero. I think you're often looking for a left-shift where you use a right shift.
I would second kaylum's comment about using a debugger; even if you flip the appropriate shifts and |
with out
properly, you're still going to have logic errors that will be easily fixed with a debugger.
Upvotes: 1