2.4 - Nature & Capabilities of Software

Download Report

Transcript 2.4 - Nature & Capabilities of Software

Binary Conversion
In today’s lesson we will link together the
binary and algorithm topics by looking at
how to get the computer to:
• convert binary to decimal
• convert decimal to binary
• do other conversion tasks – e.g. decimal
to Roman Numbers
Binary
The binary system is the same, but is based on two:
x2
x2
x2
8
4
2
1
1
0
1
1
In each column
we can have
two different
digits (0 or 1)
As we move left, the
column headings
increase by a factor
of two
This number is:
8 + 2 + 1 = 11
It’s still eleven, it’s just written
down differently
Binary Examples
128
64
32
16
8
4
2
1
0 0 0 1 0 1 0 0
= 20
0 1 1 0 0 1 0 1
= 101
0 0 0 0 1 1 1 1
= 15
0 0 0 1 1 1 1 0
= 30
Do all of the odd numbers have anything in common?
Converting to Decimal
• To convert a binary number to decimal, all
you need to do is:
– add the binary column headings
– calculate the column values by multiplying
the digits by their headings
– add up all of the column values
• This only requires simple arithmetic, so
would be easy to do using either a
programming language or a spreadsheet.
Converting to Binary
• Converting decimal to binary is a bit more
tricky
• There are two different methods that you
can use:
– a more “common sense” method,
comparing the value with the column
headings
– a more mathematical approach using
bitwise AND and the column headings
Comparison Method
• If we are converting a number to binary, we
don’t need to use any column where the
heading is bigger than the number.
• e.g. for 20, the first column we need to use
is 16
• If we have 1 x 16, then we have 4 left, so
we don’t need an 8, but we can have a 4…
• i.e. each time we use a column heading, we
subtract the heading value from the number
Bitwise AND
• For example, 20 AND 4:
128
64
32
16
8
4
2
1
0 0 0 1 0 1 0 0 = 20
0 0 0 0 0 1 0 0 =4
0 0 0 0 0 1 0 0 =4
Bitwise AND Method
• If we do a bitwise AND with the number and
the column heading, that will tell us whether
we need a 1 in that column.
• e.g. 20 AND 4 = 4 – if the answer is
anything other than zero, then we need to
put a one in that column.
• In Python we use & for bitwise AND, e.g.
if 20 & 4 > 0:
• In Just Basic we use AND, e.g. 20 AND 4
Other Conversions
• We can also use the comparison method to
convert decimal numbers to Roman numerals:
1. Order the Roman letters into order of size
2. If the decimal number is larger than the value of
the letter, we need to use that letter
3. Subtract the value of the letter from the decimal
number
4. Repeat from 2. until you reach 0
• NB. It’s slightly more complicated than that,
because, e.g. 9 is IX, but not much.