Comparing binary numbers is one of the most frequently performed operations inside a computer.
It is necessary to compare numbers to perform many arithmetic operations, but also for evaluating conditionals, executing loops, and… in many other cases.
So, just as it is necessary for a computer, we must also learn to do it “by hand”. Fortunately, comparing two binary numbers is very easy (even easier than in decimal).
Comparing unsigned variables
If our binary number represents an unsigned value, the comparison is very, very easy.
- We start from the leftmost bit
- We compare bit by bit
- If they are equal, we move to the next bit
- If they are different, the one with
1is the greater one.
Example of comparing unsigned variables
Let’s consider the binary numbers 1101 and 1011 for comparison:
1101(13 in decimal)1011(11 in decimal)
Let’s start by comparing the most significant bits:
- For
1101, the most significant bit is 1. - For
1011, the most significant bit is also 1.
Both numbers have the same most significant bit, so we move to the next one:
- The second bit for
1101is 1. - The second bit for
1011is 0.
Therefore, 1101 is greater than 1011.
Comparing signed variables
When working with signed variables, things get a bit more complicated. In signed variables, the leftmost bit indicates the sign of the number. If this bit is 1, the number is negative; if it is 0, the number is positive.
So, to compare we must do the following:
Look at the sign bit
- If it is different, the one that is positive (has a
0) is the greater one - If both are positive, compare as if they were unsigned
- If both are negative, invert the numbers, and compare as if they were unsigned.
If one is positive and the other is negative, the positive one wins. If both are positive, compare as we did before. Both cases are easy.
The only “minor difficulty” (but very minor) is if both are negative. In two’s complement, negative numbers are inverted. So to compare them we have to,
- Either invert them, and compare them
- Or simply compare from left to right (as in the case of positives), but now the one with a
0is greater
Personally, I would do the second option. But use whichever one seems more comfortable to you.
As we can see, we have to consider a couple more things. But it’s not difficult if we know what we are doing. We just need to know that now they can be positive or negative numbers.
