Having issues with some homework, C programming stuff
So the problem is to add 3 numbers together(2's complement) in C. Normally should be very simple, but the hard part of this problem is that you can only use the ops ! ~ & ^ | << >>, no kind of loops, or function calls, or anything fancy. Just those ops. He gives us a function that adds 2 words together. The return of the function I'm writing (sum3) is return sum(word1, word2). My responsibility is to determine what to set word1 and word2 to in order for the call to the sum function to give me the proper answer. Oh, and also I c开发者_运维知识库an only use 16 total of those ops up there.
I tried setting word1 to x ^ y, and word2 to (x & y) << 1 to see if I at least got the right answer from that for the first 2 numbers, and it always ends up correct. However, I have no idea how to throw z into the mix without messing everything up. I think this is is the biggest problem...somebody please help, I messed up and didn't realize this was due in 5 hours from now, so I'm freaking out. At least a good hint...something, anything.
Just a hint: a + b == (a ^ b) + ((a & b) << 1)
. Here a & b
is the expression for carry.
As you can see, by this transformation you reduce an add on N bits to some logical operations and an add on N-1 bits. If the N is given, you could manually unroll the loop and the whole result will contain only XOR, AND and SHL(1).
精彩评论