简体   繁体   中英

adding two unsigned chars

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;
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM