1

In the same way that you can simulate the if statement and functions, I am wondering if there is a way to simulate the comparison operators ==, !=, >, >=, <, <=.

For example, in JavaScript, instead of doing this:

var x = a > b

Maybe there is a way to do it in a more primitive way, such as sort of a logic circuit or something, or using bit shifts or something. I just wanted to see if there is any way to simulate such operations (just providing an example of one of them would be helpful to figure out the rest on my own).

4

Subtraction is the fundamental and more primitive mechanism: a - b vs. a > b. Following subtraction a-b most CPU's will set some flags such that we can determine: result > 0, result == 0, result < 0, which we can use for conditional branching.


Subtraction, a - b, is accomplished by addition: a + -b, and, negation (-b) is accomplished by the complement plus one: ~b + 1 (for two's complement integers).  So, a - b is a + ~b + 1.  And with appropriate carry flags we can determine greater, equal, or less, so as to infer the magnitude relationship.


Now, a + ~b + 1 requires a three input adder for the low order bit; however, any addition of bytes/words requires three-bit-input adders (to accommodate two inputs plus a carry bit) for all bit positions except just the low order bit, where there is no carry input.  Thus, the burden for +1 of negation (for subtraction) is arguably minimal: that the low order bit needs the same full adder (3-bit input) as all the other bit positions.


(Complement is simply an inversion of each bit in place, very inexpensive.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.