is there a simple way to find the smaller of two binary numbers (signed in two’s complement format), with only the following operations: bitwise logic, right shift, an add, an equality compare, and a jump if accu is negative?
I need this for an assignment to express some C snippets in a very minimal assembler language.
The only thing I came up with so far is a distinction of 3 cases:
-
If one number is negative and the other positive we have the solution there.
-
If both numbers are positive, add to both minus one and check for the first number to get zero, this is the smaller one.
-
If both are negative, make them positive i.e. take the two’s complement of both and go to step 2.
But this seems rather extensive for a “simple” less than condition.
Maybe I am just stupid and can’t see the obvious solution 🙂
Okay, first of all, you do know this is possible — those operations are all there really is for bit manipulation. So what’s, first of all, the simplest possible thing? A loop like this
When you get either A or B to zero, then that one is the smaller. Observe that this works for either two negatives or two positives. So now you have a known solution; conveniently, you have an add instruction so you don’t need to implement that.
But that’s O(n). What can you do better? (Hint: you should be able to get O(lg n).)
Consider what a right-shift is in a binary number: it’s essentially division by 2.
See if that hint helps any.
Here’s an alternate thought: if you have a word-width add, how can you turn an addition into a subtraction? If you can do that,. you can subtract A from B and see how the difference comes out.