On paper, binary arithmetic is simple, but as a beginning programmer, I’m finding it a little difficult to come up with algorithms for the addition, subtraction, multiplication and division of binary numbers.
I have two binary numbers stored as strings, assume that any leading zeroes have been dropped. How would I go about performing these operations on the two numbers?
Edit: I need to avoid converting them to an int or long.
The following code implements binary addition without actually doing any arithmetic, binary or otherwise. The actual “addition” is done by
lookupTable, and everything else is straight-up string manipulation. I wrote it with the intention of making it as instructive as possible, emphasizing the process instead of efficiency. Hope it helps.While we’re at it, I might as well do
multiplytoo.