# How to compare two binary numbers

The comparison of binary numbers is one of the operations that are most frequently performed inside a computer.

It is necessary to compare numbers to perform many of the arithmetic operations, but also for conditional evaluation, loop execution, and… in many 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.

## Comparison of unsigned variables

If our binary number represents an unsigned value, the comparison is very, very easy.

• We start with the bit on the left
• We compare bit by bit
• If they are equal, we move on to the next bit
• If they are different, the one with `1` is the larger one.

### Example of comparison of 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 on to the next one:

• 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 little 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 larger 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.

As we can see, we have to take into account a couple more things. But it’s not difficult if we know what we are doing. We just have to know that now there can be positive or negative numbers.

If one is positive and the other is negative, the positive one wins. If both are positive, it is compared 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 them
• 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 choose the second option. But use the one that seems most comfortable to you.