开发者

How to find the smaller of two binary numbers with basically only bitwise logic?

is there a simple way to find the smaller of two binary numbers开发者_如何学Go (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:

  1. If one number is negative and the other positive we have the solution there.

  2. If both numbers are positive, add to both minus one and check for the first number to get zero, this is the smaller one.

  3. 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

loop
  Set A to one closer to zero
  Set B one closer to zero
until either A is 0 or B is zero

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜