Just for fun, I decided to try to implement addition on a purely bitwise level. I came up with this:
This seems to work, num1 and num2 are added and the result is stored in sum. It just seems really cumbersome to me, particularly the way in which carries are handled.Code:void main(void) { unsigned char num1 = 19; unsigned char num2 = 6; unsigned char sum = 0; unsigned char oldcarry = 0; unsigned char place = 1; unsigned char insertshift = 7; unsigned char x; for (x = 0; x < 8; x++) { unsigned char bit1 = place & num1; unsigned char bit2 = place & num2; unsigned char bitsum = place & (bit1 ^ bit2); unsigned char newcarry = 0; sum >>= 1; if (bit1 & bit2) { newcarry = place << 1; } if (oldcarry) { if (bitsum & oldcarry) { newcarry = place << 1; } bitsum = place & (bitsum ^ oldcarry); } sum |= bitsum << insertshift; oldcarry = newcarry; place <<= 1; insertshift -= 1; } }
I know it's not commented, but I think the variable names are descriptive enough to show what's going on.
I guess I'm just looking for any improvements or suggestions. I don't do a lot of bitwise work, and I wanted the practice for a project I'm working on.