Reputation: 21
I have assignment to add two unsigned chars using shifting. s is summary, p is "overflow" i don't know how to say it. this is my code, something is wrong, it always prints 0 0
unsigned char get_bit(unsigned char x, int i){
return (x>>i)&1;
}
void set_bit(unsigned char *x, int i, unsigned char b){
*x=(b<<i)|(*x&~(1<<i));
}
void f(unsigned char x, unsigned char y, unsigned char *s, unsigned char *p){
int i;
unsigned char k=0,c=0;
for(i=0;i<8;i++){
unsigned char m=0;
m=get_bit(x,i)+get_bit(y,i)+c;
if(m==2) {
m=0;
c=1;
}
else c=0;
set_bit(s,i,m);
}
*s=(unsigned char)k;
*p=(unsigned char)c;
}
Upvotes: 0
Views: 1106
Reputation: 759
Well first you are missing the case where m == 3 (when both bits are 1 and the carry is 1).
Second you are storing your answer in s, and then you overwrite it with the value of k which is never set, so you get 0 at the end. Either remove the line *s=(unsigned char)k;
or change set_bit(s,i,m);
to set_bit(&k,i,m);
Upvotes: 1