How does an Arithmetic Logic Unit do comparisons?

4.8k views Asked by At

I am taking a course of system tools and architecture in my University and the first class is about how CPU and RAM talks and how CPU process the data. As explained by the Prof, CPU has an ALU (Arithmetic Logic unit) which performs arithmetic such as additions and comparisons. But he did not explain how it does it.

I did some searching and found this link which directs to a youtube video that explains how addition is performed - well explained for beginners. Even this link explains that CPU directs arithmetic processing to ALU but does not deal with how ALU performs it.

My question is about how an ALU does comparison. As humans, we know 5 is less than 7.

But how does an ALU know this; is it hard-coded in some way? I am sure it must use some logic for comparisons: what is that logic?

2

There are 2 answers

5
Stephen Canon On BEST ANSWER

Are you familiar with how typical ALUs set flags to indicate that overflow occurred, or that the result of an operation is zero or negative? Typically, a comparison is performed by doing a subtraction and updating the flags but discarding the numerical result.

For example, if you subtract 7 from 5, the result is negative. Therefore, 5 is less than 7.


I should note that this is definitely not the only way in which it is possible to implement comparison. With a little thought, one can construct an algorithm (which could be made into a circuit) to directly compare the binary representations of two integers without subtracting them. However, subtraction is such a fundamental operation that (almost) all CPUs implement it quite efficiently already, and there is no reason not to reuse that implementation for comparisons.

1
Ken KD5ZXG On

Chain of relays or transmission gates (74CBT3253). Pick your comparison test < = >, or use to find borrows without ripple.

Manchester Magnitude comparator:
Manchester Magnitude comparator