0

I was trying to figure out how to add bits (up to 2 bytes) using only the following bitwise operations: ~ & ^ | << >>. I've been trying for a while with no luck. I was wondering if anyone knew how.

int logicalByteAdd(int x, int y) {

return ;
}
2

1 Answer 1

2
unsigned short add(unsigned short a, unsigned short b)
{
    unsigned short carry = a & b;
    unsigned short result = a ^ b;
    while(carry != 0)
    {
        unsigned short shiftedcarry = carry << 1;
        carry = result & shiftedcarry;
        result ^= shiftedcarry;
    }
    return result;
}

Proof of Correctness provided by Mooing Duck

Sign up to request clarification or add additional context in comments.

2 Comments

Since comments can be deleted without warning, feel free to copy the link into the actual answer if you want. Or not, as you desire.
I understand this, but how can you do it without using the any functions such as while,if,etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.