[英]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. s是摘要,p是“溢出”,我不知道怎么说。 this is my code, something is wrong, it always prints 0 0 这是我的代码,出了点问题,它总是打印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). 首先,您会错过m == 3的情况(当两个位均为1且进位为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. 其次,您将答案存储在s中,然后用从未设置的k值覆盖它,因此最后得到0。 Either remove the line *s=(unsigned char)k;
要么删除行*s=(unsigned char)k;
or change set_bit(s,i,m);
或更改set_bit(s,i,m);
to set_bit(&k,i,m);
到set_bit(&k,i,m);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.