How do computers compare numbers?

493 views

Example: How does a computer know that 8 ist greater than 3?
Because it works in binary, how does it know that 1000 (8) is greater than 0011 (3)?

In: 2

8 Answers

Anonymous 0 Comments

It doesn’t know: it checks when it needs to. You could do it by checking bits from left to right and returning once the bits differ. For your example it would see that the leftmost bit of 8 is set but the leftmost bit of 3 isn’t, and so 8 is bigger than 3.

However the faster approach is simply to subtract one from the other and checking if the answer is above or below zero (or zero exactly). The subtraction command will set flags in the CPU depending if the result is zero, and if the result is above or below zero. All you need to do is call that command (which will subtract the two numbers and flip the right flags), and then check what flags got set. If the zero flag got set the numbers are equal. If the zero flag did not get set but the sign flag did the numbers are not equal and the latter one is larger than the first one. If neither flag is set the first flag is larger.

You are viewing 1 out of 8 answers, click here to view all answers.