A coworker today proposed to me a question he’d received in class about adding numbers using only bitwise ops. Being a C/C++ program of some reasonable chops I remembered that you can add/divide numbers by 2 using the bitwise shifts I didn’t immediately know if there was a way to add using only bitwise ops, just a sneaking suspicion that it wasn’t possible or any faster then using the CPU instructions (and hardware) dedicated to the task since the dawn of time. A bit of Google-ing bore out my suspicions and I imparted this knowledge to my coworker in no uncertain terms.
I’d found a bit of code that adds two numbers together using just bitwise ops and a do-while loop. I wanted to solve the “problem” so I started to think about changing the code I found for the more constrained case. Tracing through the function with real data was just giving me a headache so I just resolved myself to reinvent the world and ended up writing this: http://pastebin.com/wLMFyyrw. Yes, that’s right, it’s a recursive adder function. It works too. I only typed in random numbers up to about 7 figures, so YMMV. Quite possibly the dumbest thing I’ve ever written but am still proud of.