Addition of binary integers
Introduction
We've now seen how to represent both positive and negative numbers in binary. Before we look at adding some numbers, let's look the rules of binary addition.
-
- Zero plus zero = zero! In binary, 0 + 0 = 0 (0 is the binary equivalent of zero)!
- One plus zero (or zero plus one) = one! In binary, 1 + 0 = 1 (1 is the binary equivalent of one)!
- One plus one = two! In binary, 1 + 1 = 10 (10 is the binary equivalent of two).
- One plus one plus one = 11 (11 is the binary equivalent of three).
- One plus one plus one plus one = 100 (100 is the binary equivalent of four).
- And so on.
Let’s look at some examples. Before we do this, you should note how we refer to bits in a byte. The bit on the left, the Most Significant Bit (MSB) is called bit 7. The bit that is worth the least, the one on the right hand side (Least Significant Bit, or LSB) is referred to as bit 0. In computing, we more often than not start counting from zero rather than 1.
Remember the convention. Bit zero is on the right hand side. Bit seven is on the left. Starting on the right hand side, just as if we were adding decimal numbers, we follow the rules we described at the beginning of this section.
Example 2
Add 15 to 15 in pure binary, using a byte for each number.
The binary equivalent of 15 is 0000 1111
So we need to do the sum:
Starting on the right hand side, just as if we were adding decimal numbers, we follow our rules for adding bits. This gives us:
We can double-check our answer. 0001 1110 is the same as 16 + 8 + 4 + 2, 0r 30 in decimal. We are correct! Notice how the carry bits were used and shown in our calculation. It is always a good idea to show your working when doing arithmetic.
Example 3
Add 150 to 140 in pure binary, using a byte for each number.
The binary equivalent of 150 is 1001 0110
The binary equivalent of 140 is 1000 1100
So we need to do the sum:
Starting on the right hand side, just as if we were adding decimal numbers, we follow our rules for adding bits. This gives us:
Something strange has happened! We have generated a carry. Our answer needs to be in a byte, but we can’t hold the answer in a byte. We can if we have 9 bits, but our byte only has 8 bits.
If ever you add some pure binary positive numbers together and you generate a carry, then you must disregard the answer. This is because the biggest number an 8-bit byte can hold is 255 and the answer is bigger than this (indicated by the fact that you have a carry bit).
If this ever happens in a program, an error message would be displayed. The error message is known as an overflow error. It means that an answer was generated but it was too big to store in the data structure set up for the answer. Our carry bit in this instance could also be referred to as an overflow bit. It’s also possible to have an underflow error. This is generated when the answer is too small to be represented in the data structure set up for it.