Add binary representation of two integers

Given two integers, add their binary representation.

 


For example,

Input:
x = 12731 (which is 0011000110111011 in binary)
y = 38023 (which is 1001010010000111 in binary)

Output: 1100011001000010
 

Input:

x = 1023 (which is 0000001111111111 in binary)
y = 1023 (which is 0000001111111111 in binary)

Output: 0000010000000000

 


 

Binary addition is much like decimal addition, except that it carries on a value of 2 instead of a value of 10. For example in decimal addition, if we add 9 + 6 we get 16 which in the sum gives a digit 6 and a carry of 1. Binary addition follows the similar logic.

  • when we add 1 and 1 (with carry of 0); the result is 2 in decimal, but since 2 is written as 10 in binary, we get, after summing 1 + 1 in binary, a digit 0 and a carry of 1.
     
  • Similarly, if we add 1 and 1 (with carry of 1), the result in 3 in decimal which is 11 in binary. So after summing 1 + 1 + 1 in binary, we get a digit 1 and a carry of 1.

Therefore in binary,

0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 10 (which is 0 with carry 1)

with carry 1
0 + 0 (+ 1) = 1
0 + 1 (+ 1) = 10 (which is 0 with carry 1)
1 + 0 (+ 1) = 10 (which is 0 with carry 1)
1 + 1 (+ 1) = 11 (which is 1 with carry 1)

 

So the idea is to extract each bit from both integers one by one from LSB to MSB and store their addition result in an array of size of integer. If addition results in a carry, we propagate the carry to next pair of bits. Below implementation uses LEFT shift and AND binary operator.

C++

Download   Run Code

Output:

x (12731) in binary is 0011000110111011
y (38023) in binary is 1001010010000111

x + y is 1100011001000010

Check similar implementation using RIGHT shift and AND binary operator here.
 

Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂