Binary mathematics

<< Previous: Hexadecimal and binary Next: Characters >>

Binary addition

The following rules apply to binary addition.

Binary addition rules
0 + 0 = 0
0 + 1 = 1
1 + 1 = 0 carry 1
1 + 1 + 1 = 1 carry 1

As we know from basic mathematics 1 + 0 is the same as 0 + 1. It also doesn't matter how many other times you add 0. Similarly any combination of 1, 1 and any amount of 0s is still the same as 1 + 1.

Example

For our example let's add the binary numbers 10010011 and 00011010

The first step is to draw out a table and fill it in with the column headings for binary. Remember, the column headings in binary start at 1 on the right and double as you move left like below.

Carries 1 1 Decimal
Number_1 1 0 0 1 0 0 1 1 147
Number_2 0 0 0 1 1 0 1 0 26
Answer 1 0 1 0 1 1 0 1 173

In an exam question it is essential to always clearly show your carries as if your working is clear and you make a small error you may gain part marks.

Test yourself

Carries
Number_1
Number_2
Answer

Generate a sum, do the addition and check your answer below



Overflow errors

To understand overflow errors you have to understand something called the program word. Essentially processors work with data split into certain word sizes. That is the number of bits used for each piece of information. If we consider a program word of 8 bits it means this is all we have to store a value in. If we were to add two 8-bit numbers and the result was too large to store in 8-bits then we have an overflow error.

Carries 1 1 1 Decimal
Number_1 1 0 0 1 0 0 1 1 147
Number_2 1 0 0 1 1 0 1 0 154
Answer 1 0 0 1 0 1 1 0 1 301

In the example above the most significant bit would be ignored and it would wrongly store 45.

Bitwise shifts

Bitwise shifts can be used to multiply or divide numbers by powers of 2 simply by moving all the bits of a binary number a certain number of places to the left or right. Gaps are then filled in with 0s.

As you can see in the example below when we bit shift left we double the number each time. So if we bitshift left by 2 places we multiply the number by 4. If we shift 3 places we multiply by 8 and so on.

A left shift will multiply our number by 2n where n is the number of places we shift to the left.

Columns 128  64  32  16  8   4   2   1  Decimal
Number 0 0 0 0 0 1 1 1 7
Leftshift1 0 0 0 0 1 1 1 0 14
Leftshift2 0 0 0 1 1 1 0 0 28
Leftshift3 0 0 1 1 1 0 0 0 56

When we right shift we divide our number as can be seen in the example below.

A right shift will divide our number by 2n where n is the number of places we shift to the right.

Columns 128  64  32  16  8   4   2   1  Decimal
Number 0 0 1 1 1 0 0 0 56
Rightshift1 0 0 0 1 1 1 0 0 28
Rightshift2 0 0 0 0 1 1 1 0 14
Rightshift3 0 0 0 0 0 1 1 1 7

There is a problem when we shift a 1 out as we right shift. Instead of performing /2 it performs //2 and ignores the remainder.

<< Previous: Hexadecimal and binary Next: Characters >>

© All materials created by and copyright S.Goff