You can add two numbers without using arithmetic operators by using bitwise operators. This is mainly a binary level manipulation. Bitwise operators include AND (&), OR(|), XOR()̂, Left Shift(<<), and Right Shift(>>) operators. To perform addition without an arithmetic operator, half adder logic is used, which is a basic single bit adder designed using XOR and AND gates. The XOR gate works as the ADDER while the AND gate works as Binary Carry calculator.
Below is the method in Python for adding two numbers without using arithmetic operators:
def add(a, b):
# Iterate till there is no carry
while (b != 0):
# carry now contains common set bits of a and b
carry = a & b
# Sum of bits of a and b where at least one of the bits is not set
a = a ^ b
# Carry is shifted by one so that adding it to a gives the required sum
b = carry << 1
return a
# Test this function
print(add(20, 30))
In this code:
1. The expression ‘carry = a & b‘ produces a binary number that has ’1’s where ’a’ and ’b’ both have 1’s. That’s why it’s called carry - these ’1’s should be carried over and added to the next power of two.
2. The expression ‘a = a b̂‘ produces a binary number that has ’1’s where ’a’ and ’b’ have ’1’s exclusively - when ’a’ has ’1’ and ’b’ has ’0’, and vice versa. So, this step provides a partial sum.
3. The carry is then shifted one bit to the left ‘(carry << 1)‘ and added to the partial sum in the first step.
4. The while loop continues until there is no carry, which means that all ’1’s that should be carried over and added have been added.
Note that the code example given is in Python, however one can use the same logic to write this function in many other languages. The code might not work with languages in which bitwise operations do not work well on the signed numbers. Bitwise operation works perfectly fine with unsigned numbers in C/C++. It’s important that you confirm whether bitwise operation works as expected for signed numbers in all cases your programming language.
Let’s understand this using an example:
If we want to add 2(0010) and 3(0011),
Step 1. Carry = a & b = (0010) & (0011) = 2 (0010)
Step 2: a = a b̂ = 23̂ = 1 (0001)
Step 3: b = carry << 1 = 2 << 1 = 2*2 = 4 (0100)
Then, repeat these steps:
Step 1: Carry = a & b = 1 & 4 = 0 (0000)
Step 2: a = a b̂ = 14̂ = 5 (0101)
Step 3: b = carry << 1 = 0 << 1 = 0 (0000)
Now, ’b’ becomes ’0’ so we end the loop and return ’a’ as the sum, which is indeed 5.