// C++ Program to add two numbers without using arithmetic operator. // bitadd.cpp // Built with : g++ -o bitadd -std=c++11 -Wall -O3 bitadd.cpp #include #include #include #include #include #include #include // uncomment one of these // typedef int32_t my_int; typedef int64_t my_int; my_int Add(my_int x, my_int y) { // Iterate till there is no carry while (y != 0) { // carry now contains common set bits of x and y my_int carry = x & y; // Sum of bits of x and y where at least one of the bits is not set x = x ^ y; // Carry is shifted by one so that adding it to x gives required sum y = carry << 1; } return x; } using my_list_type = std::vector< std::pair >; int main() { my_list_type ops = { { 0, 1 }, { 1, -1 }, { 69, -42 }, { 42, 69 }, { -42, 69 }, { -42, -69 }, { 256, 512 }, { 123456789, 1 }, { 2147483647, 1 }, { -2147483648, 1 } }; my_int sum0, sum1; std::cout << "sizeof my int = " << sizeof(my_int) << "\n"; for (const auto& c : ops) { sum0 = c.first + c.second; sum1 = Add(c.first, c.second); if (sum0 != sum1) { std::cout << "oops!\n"; } std::cout << c.first << " + " << c.second << " = " << sum0 << " (" << sum1 << ")\n"; } return 0; }