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 cases.
So, just as it is necessary for a computer, we also need to learn to do it “by hand.” Fortunately, comparing two binary numbers is super easy (even more so than in decimal).
Comparison of unsigned variables
If our binary number represents an unsigned value, the comparison is very very easy.
- We start with 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
1
is the greater.
Example of comparing unsigned variables
Let’s consider the binary numbers 1101
and 1011
to compare:
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:
- The second bit for
1101
is 1. - The second bit for
1011
is 0.
Therefore, 1101
is greater than 1011
.
Comparison of 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 need to do the following:
- Look at the sign bit
- If they are different, the one that is positive (has a
0
) is greater - 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 they are different, the one that is positive (has a
If one is positive and the other is negative, the positive one wins. If both are positive, it’s a comparison as we did before. Both cases are easy.
The only “mini difficulty” (but very mini) 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
- Or simply compare from left to right (as in the case of positives), but now the one with a
0
is greater
Personally, I would go with the second option. But use whichever you find more comfortable.
As we see, we need to keep a couple of other things in mind. But it is not difficult if we know what we are doing. We just need to know that they can now be positive or negative numbers.