The software developer’s view of the hardware

247 247 HSC Course
19
The software developer’s view
of the hardware
In which we look at what goes on under the hood to make everything happen
Tere’s not really any need to understand how it is that a computer
does what it does. Just as you can drive a car without knowing how
an internal combustion engine works, the same goes for using and
programming a computer. In the early days of computing though, this
wasn’t the case. Te frst computer programmers were the engineers
who built the computers, without an intimate understanding of how
everything in the machine worked, it was impossible to do anything.
In the early days of home computing the same applied. Te frst home
computers available in Australia were microprocessor evaluation kits
which were programmed directly in binary or machine code, so you
really needed to understand exactly how things worked. Tis has of
course changed and very little of how a computer works is visible
at the level of programming most people use. One of the few places
you can be aware of the way the computer does things is in variable
types. Variable types in C# are based upon the way the processors in
a modern computer represent data. Understanding this link will help
you write more emcient code.
The software developer’s view of the hardware Representation of data within the computer
248 249 HSC Course
Representation of data within the
computer
Everything in the computer, and on storage media is stored as binary
codes in transistors within the silicon making up the computer’s cir-
cuitry. Normally we write these as 1s or 0s, but you really could call
them anything you wanted — we’ll stick to the 1 and 0 convention.
What is important to realise right from the beginning is that the bits
of data have no inherent meaning at all they are just stored electri-
cal signals, the meaning comes from the way sofware and hardware
interprets that data. A particular collection of bits could be a number
representing a bank balance, a colour record, part of an mp3 music
fle, pixels in an image — it will all depend on what the other sofware
(which is itself just a collection of bits) does with the data. Keep this
principle in mind and you won’ t be confused when you realise that
00111000 is both the letter ‘H’ and the number 56.
Character representation
Computer systems store text, lots and lots of text. Important text such
as books like this and unimportant text like spam emails. Because
computers were originally developed in countries where English was
the dominant language, the frst representations of text were made
to match the Roman alphabet used in those countries. English uses
52 letters (26 upper case and 26 lower case), 10 digits and a couple
of dozen punctuation characters. All up, you need about 96 diferent
codes to cover everything. Using seven binary bits in a row gives you
128 diferent possible combinations, so this length was chosen, the
frst 32 codes (0-31) were used for controlling printers and the last 96
(32-127) were used for all the printable characters. Tis system was
formalised as the ASCII' system (now called the 7-bit ASCII code).
Other systems were invented by other computer manufacturers, nota-
bly EBCDIC by IBM, but ASCII won and now all computers use it.
Of course, not everyone speaks English, so as computers became
more common, there was a push to include more characters so people
speaking other European languages could type words such as ‘façade’
without having to go back with a pen to add accents to the letters. So
ASCII got extended from 7-bits to 8-bits and called ‘Extended ASCII’
although most people just say ‘ASCII’ now. Te extra characters from
128 to 255 cover all the accented letters in most European languages,
the 48 letters of the Greek alphabet and a few extra symbols.
Of course it wasn’t long before people outside of Europe mentioned
that they’d like to use computers too, and many of their languages had
1 American Standard Code for Information Interchange
considerably more characters than you could ft into a scheme that
allowed 256. Something else was needed and so Unicode´ was born.
Unicode is a system that is used to encode all characters in all written
languages. At the time of writing Unicode supports over 100,000 dif-
ferent characters and symbols used in languages and dialects all over
the world. ASCII is still there in the frst part of the UTF-8 encoding,
up to 32-bits are used to extend the system. If you are writing sofware,
then you should be supporting Unicode in your programs as it means
users around the world can input data in their local languages, even if
your program continues to show only English instructions.
Unicode has gone even further than just modern languages, extending
to have characters for hieroglyphics, cuneiform, musical notations
used in the Byzantine era, and even imaginary fonts such as Klingon
and Elvish (although they’re not omcial).
Representing sentences and longer sequences of characters in the
computer is simply a matter of setting enough memory aside to hold
all the characters. Tere are two ways of marking a string so that the
sofware knows how long the string is. Te Pascal system, which was
used by FORTRAN and COBOL and many other languages but isn’t
used much any more, started each string with an integer which counted
the number of characters. Tis meant that Pascal format strings are
limited to 255 characters. Te C method, and hence the one used by
C#, is to put a terminating value, a 0, as the last character in the string,
that way a string can potentially be as long as is needed. Finishing
with a terminating value is a little easier to program, but in modern
languages, there is little need to worry about this as the string functions
built into the language will just do the job as needed.
Te only thing you need to really know about strings as they efect
programming is that they are necessary, but inemcient. In most lan-
guages whenever you add something to a string the computer actually
copies the old string with the change made, and then removes the old
string. If the string is long, this is quite time consuming. C# adds a
StringBuilder class to the language which works diferently, and
much more emciently if you are going to make strings up by adding
bits together, which is quite a common programming technique.
Integer representation
Everyone knows that computers work with numbers. When microproc-
essors were frst introduced this wasn’t 100% true, when microproces-
sors frst came out, they worked with integers, but not other numbers,
to get them to work with fractions took considerable low level program-
ming. One of the frst improvements made to microprocessors was the
2 http://unicode.org/
Example — Convert 87,, to
binary
87 ÷ 2 = 43 r 1
43 ÷ 2 = 21 r 1
21 ÷ 2 = 10 r 1
10 ÷ 2 = 5 r 0
5 ÷ 2 = 2 r 1
2 ÷ 2 = 1 r 0
1 ÷ 2 = 0 r 1
Writing the remainders from
the bottom to the top = 1010111
so:
87,, = 1010111¸
If you were asked for an 8-bit
number, simply add a 0 to the
lef of the number, you can add
as many zeroes as needed with-
out it changing the value of the
number — just as 0134 and 134
are the same number.
The software developer’s view of the hardware Representation of data within the computer
250 251 HSC Course
addition of a foating point unit, a
part that could handle fractions in
calculations. Let’s start with inte-
gers though. An integer is a whole
number, one that you could use to
count the number of people on a
bus, 1, 27, -3876 are all integers
2 ½ isn’t.
CPUs have a ‘natural’ integer
size, a size that is built into them.
Te frst readily available CPUs
used 8-bits in their calculations,
so they could represent posi-
tive integers from 0 to 255. Te
16-bit processors that replaced
them could handle a range of
0 to 65 535. When computers
became really popular for people
at home, they used 32-bits for integers, so numbers 0 to 4 294 967 295
were possible; and as this book is being written, 64-bit processors
are in most new computers meaning positive integers from 0 to
18 446 744 073 709 551 615 can be easily used inside programs. For
the rest of this section (and in the HSC itself) we’re going to limit
ourselves to 8-bit integers. Tis doesn’t matter, all the techniques we
look at with 8-bit integers are exactly the same for any other imple-
mentations, it’s just quicker to use fewer bits.
One of the important things you need to be able to do with binary
numbers is to convert them to and from decimal numbers`. Tere
are a number of ways to do this, the method explained here isn’t the
fastest, but it is the easiest, and fairly easy to learn.
1. Start with a decimal number, divide it by 2 and leave the remainder.
2. Divide your answer from step 1 by 2 and again leave the remain-
der.
3. Repeat steps 1 and 2 until you reach 0 as the number to divide.
4. Write all the remainders in order starting with the last one and
working to the frst one. Tat number is the binary equivalent of
the decimal number.
It’s a pretty easy process once you’ve done it a few times. Te only pos-
sible complication is that in the HSC examination you’re not allowed to
use a calculator, so you’ll have to do the dividing (and the multiplica-
tion that comes later) in your head — so don’t start using a calculator
3 Decimal numbers are just those that you’re used to using every day,
they are called decimal because they are based on 10. Binary is based on 2.
now to make it easier, do all these examples and exercises without,
that way you’ll be prepared for the HSC.
You’ll need to able to convert back too — from binary numbers to
decimal numbers. Again, this is fairly simple once you practice a
couple of times. Again, there are a number of ways of doing this, the
one here is just one particularly simple way.
1. Start by writing, from right to lef 1, 2, 4, 8, 16, 32, 64, 128 (you
don’t have to remember them, each number is just double the
one to the right.
2. Write the binary number with one digit under each of the num-
bers you wrote in step 1.
3. Cross out any number that has a 0 under it.
4. Add up the remaining numbers and the result is the decimal
equivalent.
Te obvious question about all of this is how useful is it in everyday
programming — to be perfectly honest, not very useful at all. All mod-
ern programming languages look afer all of this for you, but there will
be questions about this in the HSC, so you need to know it for that.
So practice, these are a few easy marks in the exam.
Positive integers are not the only integers a computer deals with, it
can deal with negative integers too. While there is a simple corre-
spondence between positive binary numbers and decimal numbers
(it comes from simple arithmetic) there isn’t a correspondingly simple
one for negative numbers — in fact there are three diferent common
methods of representing negative integers in the computer. Which of
them actually means a negative binary number is up to the operating
system and the programming language.
Te frst thing to know about binary numbers is that they still use the
same number of bits as a positive number, that means that if you are
using an integer system that includes negative numbers your possible
range changes. We already know that if we have 8-bit positive binary
numbers, then the available range of numbers is from 0 to 255. If we
are using negative numbers, then the range is -128 to +127 (or -127 to
+127 depending on the scheme). Of course you can’t mix positive and
negative representations and expect them to work, if you’re working
with positives, then you have to use all positives, if you’re working
with negatives, then you can only use positives that are within the
range permitted. Again, with modern programming languages all this
is taken care of for you, so you don’t have to worry.
Example — Convert 01010111¸ to decimal
128 64 32 16 8 4 2 1
0 1 0 1 0 1 1 1
Cross out the numbers above the 0s.
128 64 32 16 8 4 2 1
0 1 0 1 0 1 1 1
Add up the remaining numbers
64 + 16 + 4 + 2 + 1 = 87
So, 01010111¸ = 87,, as we would expect from the earlier example.
Tis shows one of the advantages of this section of the course, you
can check your answers are correct when doing the exam.
Endian-ness
Tis is one of those things that
professional programmers
probably don’t have to worry
about any more, but it’s useful
to know.
Although everyone agrees how
to turn a decimal number into
a binary number, there was no
consensus between CPU man-
ufacturers as to which byte of
a multibyte integer should go
frst. Some manufacturers put
the lowest value byte in the
lowest memory position, then
the higher value bytes in order
afer that — these are the little
endians. Other manufactur-
ers put the highest value byte
frst and then the progressively
lower ones afer that — these
are the big endians.
Numbers in English are gen-
erally big endian, we say
“two hundred and ffy eight”,
although sometimes a poet
will insist on being contrary
and having “four and twenty
blackbirds baked in a pie”.
Endian-ness only becomes a
problem when data is trans-
ferred from a computer using
one system to a computer using
the other, so special measures
are taken in this circumstance
to avoid problems.
The software developer’s view of the hardware Representation of data within the computer
252 253 HSC Course
Negative numbers using sign bits
Te simplest form of negative number is simply to use the lef most bit
(also called the most signifcant bit) as a sign bit. If this bit is 0 then
the rest of the number is positive, if the sign bit is 1 then the rest of
the number is negative. We know that 01010111¸ is 87, so 11010111¸
is -87 if we are using sign bits.
It is important to note that both 00000000¸ and 10000000¸ represent
zero but the second version is generally considered an error.
Negative numbers using one’s complement
Te next form of negative number is the one’s complement. To make
a one’s complement number you simply swap all the 1s for 0s and 0s
for 1s. 01010111¸ = 87,, so 10101000¸ = -87,,. Notice that the most
signifcant bit in the -87 representation is a 1, and it will always be a
1 for negative numbers, but it’s not a sign bit, it’s part of the number
it just acts like a sign bit.
Note again that both 00000000¸ and 11111111¸ represent zero; the sec-
ond version although correct is considered an error in most systems.
Negative numbers using two’s complement
Te third form of negative numbers is the two’s complement form and
you’re probably wondering why there’s yet another form. Tis form
of negative number is the one that you have to use to do calculations,
which we’ll see later on. To make a two’s complement number, you
frstly make a one’s complement, and then add 1 to it. We’ll cover add-
ing 1 later in this chapter, so the examples now will be simple ones.
87,, = 01010111¸ so the one’s complement is 10101000¸ if we add 1 to
that we get 10101001¸ and that’s the two’s complement.
So, with three representations which do you choose? If you were being
forced to do binary arithmetic, you’d use two’s complement because
it’s the only one that works. Otherwise, it doesn’t matter. If you’re
working in any modern computing language all that is hidden by the
implementation of the language on the computer.
It’s important to note that with each of these representations of negative
numbers, the positive numbers don’t change. So, for example, the twos
complement of +87,, is as you would expect 01010111¸ — it’s only the
negative numbers that change.
Binary digits Octal digit
000
0
001 1
010 2
011 3
100 4
101 5
110 6
111 7
Table 19.1 - Binary to octal and octal
to binary conversion table.
Binary digits Hexadecimal
digit
Binary digits Hexadecimal
digit
0000 0 1000 8
0001 1 1001 9
0010 2 1010 A
0011 3 1011 B
0100 4 1100 C
0101 5 1101 D
0110 6 1110 E
0111 7 1111 F
Table 19.2 - Binary to hexadecimal and hexadecimal to binary conversion
table.
Other representations
Writing all those 1s and 0s becomes pretty tedious so there are other
ways of representing binary data. Tere are two common ones, and
you need to know both for the HSC. Octal is the base 8 numbering
system, it uses the digits from 0 to 7 each of which represents 3 bits
in the binary number. To convert a number from binary to octal start
by breaking the binary number into groups of three, starting from
the right. If the frst group doesn’t have three binary digits in it, then
add one or two 0s to the lef.
Te other system used, and this one is now much more widely used,
is the hexadecimal system (also referred to as the hex system). Hexa-
decimal, or base 16 breaks the binary number into groups of 4 digits
and then represents them using the digits 0-9 and A-F (A to F are
used because there are only 10 distinct digits in the Hindu-Arabic we
use and you need 16 digits for hexadecimal). Again, you break the
binary number up starting at the right, and add 1, 2 or 3 zeros to the
lefmost group if it doesn’t already contain 4 bits.
All this might seem very theoretical, but hexadecimal is still used in
modern computing. One of the common places it turns up is in the
representation of colour data. On of the big improvements in comput-
ers over the past 20 years has been their ability to display a wide range
of colours on the screen. Te original IBM personal computers could
display 16 colours, the frst colour Macintoshs could handle 256. All
modern computers can handle millions of colours. To specify a colour
either 24 or 32 bits are used. 24 bits are called RGB colours, 32 bits are
ARGB colours — the diference that the A part of a 32 bit colour can
be used to represent the transparency of a colour when combining
images. On a screen, all colours are 24 bit when displayed.
Each of the four components
of a colour represents 8 bits of
information and so ofen that
is represented as a pair of hexa-
decimal digits. For example, a
50% transparent light blue col-
our would have components A
= 80,, R = A0,, G = B0,, B =
FF,, and would be written out
as 80A0B0FF,, or more likely as
0x80A0B0FF (the 0x at the start is
the standard way of representing
a hexadecimal number in C# and
other programming languages).
To someone used to dealing with
colours, being able to see the 4
The software developer’s view of the hardware Representation of data within the computer
254 255 HSC Course
components like that means that
they will know that there’s lots
of blue, a bit less green and red
and so the resultant colour will
be a light blue. If this number was
written out as decimal it would
be 2 158 014 719 and that doesn’t
convey anywhere near the same
amount of information even
though it is the same number.
Representation of
fractions
Integers aren’t the only type num-
bers that your sofware will use,
fractions are important too. Frac-
tions are more properly called
foating-point numbers because
a fraction implies one number
divided by another while a foat-
ing-point just means that the number has a decimal point somewhere
and so also includes irrational numbers such as e and pi. Floating
points are used throughout sofware, in C# they are available as the
Hoat and double types. C# also has a fxed-point representation
called decimal that is used for currency calculations where the
rounding that happens in foating point numbers isn’t allowed.
Floating point numbers are handled inside the processor by the foating
point unit (FPU) which is designed to work quickly with these types
of numbers. Even with such help though foating-point numbers are
much slower to use than integers, so only use them if you have to.
Tere is a standard for the use and implementation of foating point
numbers in computers, it’s called IEEE 754-2008. It has four recom-
mended implementations a 32-bits, 64-bits, 96-bits and 128-bits. We’ll
look at the IEEE 32-bit system.
Te frst step is converting a decimal number with digits to the right
of the decimal point into it’s binary representation. Let’s start with the
number 57.37485.
1. Split the number into it’s two halves, the right and lef sides of the
decimal point.
2. Convert the integer part in the same way as before, in this case.
3. To convert the fractional part, double the fraction. Write the in-
teger portion of the result down, and then discard it if it was a 1.
4. Repeat step 3 until you have a total of 24 binary digits, including
the digits you got from the conversion of the integer part.
5. Write the integer part, followed by a binary
point ‘.’ and then the binary fraction. Tis is
the true binary representation of the num-
ber, however it’s not the representation used
by the computer — it couldn’t be, there’s no
way of storing that dot.
6. To make the representation used by the CPU
you need to do the following. If the number
you started with was greater than 1, move
the binary point to the lef until there is just
a 1 to it’s lef, count the number of spaces you
moved it, this number is called the exponent.
If the original number was less than 1, the
move the binary point to the right until there
is a 1 to its lef; again count the number of
places you moved it, but this time that num-
ber is negative.
7. Te number that is lef (the one that starts
with 1.) is called the mantissa.
8. Add 127 to the exponent. Tat means if your
original number was bigger than 2 you’ll get
a number bigger than 127, if the original
number was less than 1, you’ll get a number
less than 127 — and if it was between 1 and
two, you’ll get 127. Convert the exponent +
127 into a binary number.
9. Now it’s just a matter of writing out the bits.
Start with a sign bit, put a 0 if the original
number was positive, a 1 of it was negative.
10. Write the 8 bits of the exponent + 127.
11. Write the 23 bits of the mantissa leaving of
the 1. that it starts with — this means you are
only writing down the fractional part of that
number. Note, the . doesn’t go anywhere.
12. Te 32 bit number you now have is the bi-
nary representation of the fraction.
Simple, isn’t it. Actually, it’s not dimcult, it’s just
that there are a lot of steps and you need to prac-
tice it a few times to get the hang of it. Tere are
some exercises on page 279 that you can try, and
there are worked answers for them on page 299. Now, these conver-
sions might put you of programming as a career, but rest assured,
pretty much the only time you are ever going to need to do these is
for the HSC exam, in real life, very few programmers ever need to do
this (in fact many would have no idea how to go about it).
Example — Convert 57.34765 to binary
57 ÷ 2 = 28 r 1 0.34765 × 2 = 0.69530
28 ÷ 2 = 14 r 0 0.69530 × 2 = 1.39060
14 ÷ 2 = 7 r 0 0.39060 × 2 = 0.78120
7 ÷ 2 = 3 r 1 0.78120 × 2 = 1.56240
3 ÷ 2 = 1 r 1 0.56240 × 2 = 1.12480
1 ÷ 2 = 0 r 1 0.12480 × 2 = 0.24960
0.24960 × 2 = 0.49920
0.49920 × 2 = 0.99840
0.99840 × 2 = 1.99680
0.99680 × 2 = 1.99360
0.99360 × 2 = 1.98720
0.98720 × 2 = 1.97440
0.97440 × 2 = 1.94880
0.94880 × 2 = 1.89760
0.89760 × 2 = 1.79520
0.79520 × 2 = 1.59040
0.59040 × 2 = 1.18080
0.18080 × 2 = 0.35160
57,,= 111001¸
0.34765,, = .010110001111111110¸
57.034765,, = 111001.010110001111111110¸
Move the binary point to the lef 5 positions to get:
1.11001010110001111111110 × 2° (or 10'"' in bi-
nary)
Te 23 bits to the right of the binary point become
the mantissa, the 1 to the lef is dropped.
Te 101¸ of the exponent is added to 01111111¸
(127,,) to make the exponent part of the number,
in this case 10000100¸.
Te whole number is then bundled into a 32-bit
form starting with a sign bit (0 for positive, 1 for
negative), the 8 exponent bits and then the 23 man-
tissa bits.
01000010011001010110001111111110
Example — Convert 01010111¸ to octal
01010111 becomes 001 010 111 when we break it into 3s and add a
0 to the beginning. Either by using the table provided or by calculat-
ing in your head, convert each group to the octal digit.
001 010 111 becomes 127,
Example — Convert 01010111¸ to hexadecimal
01010111 becomes 0101 0111 when we break it into 4s. We don’t
need to add any 0s to the lefmost group as it already contains 4
digits. Either by using the table provided or by calculating in your
head, convert each group to the hexadecimal digit.
0101 0111 becomes 57,,.
The software developer’s view of the hardware Representation of data within the computer
256 257 HSC Course
Te frst three are as you’d expect (I hope) it’s only the last one that
might look confusing, but remember, this is binary, so there’s no 2.
You get the same situation as when you add 5 + 5 in decimal, there’s
no single digit that represents the sum, so you write 0 and carry 1 to
the next column to the lef.
Of course you’re expected to be able to add more than just two binary
digits, you should be able to handle the addition of 8-bit bytes (and
if you can do them, by extension you can do any number of bits).
Te HSC tends to ask for 8 bit or smaller calculations, afer all, going
further doesn’t prove anything more.
If you’re adding 8-bit bytes, it’s just a matter of adding each pair of bits
from the bytes, and possibly a carry from a previous column — this is
just like addition from primary school. If you’re adding with a carry,
then it is possible to get 1 + 1 + 1 which equals 1 with a 1 carried
over. If you get to the end and still have a 1 to carry, just put it on the
lef and make a 9-bit number. Tis doesn’t matter on paper, but in
the CPU it would cause an overfow error which may or may not be
handled gracefully by the operating system. One of the advantages of
having 32 and 64-bit processors is that they can handle much larger
numbers without overfowing.
Whenever you do a binary calculation, it’s a good habit to convert
the answer back to decimal to check if you got it correct. Especially
if you have time during an exam, you can check if you got the marks.
Incidentally, it’s a really bad idea to cheat and work out the answer in
decimal and then convert back, generally you’re going to be marked
on the working and steps in solving the problem, not on getting the
fnal answer, and it’s pretty obvious if you don’t do the steps.
Subtraction
Te good news is, you already know everything you need to know to
do subtraction. As you’d know from maths, subtracting is the same as
adding a negative number; you know how to make a negative binary
number and you know how to do addition; it’s the same for binary
numbers. Te only thing you need to be careful about is that you use
the correct version of a negative binary number, that is, you have to
use the two’s complement negative (from page 252). Te other forms or
negative can’t be used for calculations.
When you do the subtraction it is possible that you will get an over-
fow from the last bit to the 9th bit — unlike for addition, you don’t
write this extra bit down, you just forget about it. Te other thing to
remember is that the answer to a subtraction will be in two’s comple-
ment form, now if the answer is positive then this is not a problem
because the two’s complement of a positive number is exactly the same
Now, you might think that the next thing to learn would be how to
convert these fractions back to decimal numbers. However, the HSC
syllabus doesn’t specify that you have to, just that you recognise the
representations. If you’re really interested in how to go about it, I’ve
included the method in “Converting foating point numbers back to
decimal” on page 283.
Binary arithmetic
Everyone knows that computers are good at doing calculations, so it’s
not surprising that as a programmer you are expected to know at least
the fundamentals of binary arithmetic. Now, you’re probably going to
think that like foating point conversions, this is material you’ll need
to know for the HSC and not otherwise, but surprisingly some of this
can be useful in real computing — especially the boolean logic later
in this chapter.
Tere are four basic operations you are expected to do with binary
numbers: addition, subtraction, multiplication and division. It will
help if you can remember how you used to do arithmetic in primary
school, as you are going to need some of the techniques you learned
there, and possibly haven’t used since. And just a reminder, you’re not
allowed to use a calculator in the HSC exam, so don’t use one here.
Addition
Addition is pretty straightforward, as you’d expect, there are only two
digits to worry about; so there are only four possible ways they can
add up:
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 10 (that’s 0 with 1 carried over)
Add 53,, to 104,,
Firstly convert both numbers
to their binary representations
53,, = 00110101¸
104,, = 01101000¸
Now, add the pairs together
with carries as needed.
0 0 1 1 0 1 0 1
0 1 1 0 1 0 0 0
1 1 carries
1 0 0 1 1 1 0 1 total
If you convert this back to a
decimal number you get 157,,
which is the correct answer.
Sign bit
0 for +ve
1 for -ve
Exponent
127 + exponent value
Fraction
Figure 19.1 - e IEEE 754-2008 representation of a oating point binary number in 32-bit format.
e standard includes representations up to 128 bits.
The software developer’s view of the hardware Electronic circuits to perform standard software operations
258 259 HSC Course
Te frst step, is as always to convert the numbers
to binary representations, and to calculate the
two’s complement of the divisor — you’re going
to need it for the subtractions. It’s also helpful if
you can do simple binary to decimal conversions
in your head (up to 4 bits is enough).
Figure 19.2 on page 260 shows the steps in a binary
division. Te points to remember are that when
you do the subtraction of the divisor (by adding
the two’s complement) just do the number of dig-
its necessary and you can drop any overfow bits.
None of these calculations are dimcult, ut they
do need some practice until you get the hang of
them, so there are plenty of exercises at the end
of the chapter with worked solutions in the back.
Electronic circuits to perform standard
software operations
Clearly there must be some electronic way of doing all of these arith-
metic and other operations, because computers are electronic devices,
surprisingly though there are just a few very simple devices that do the
work. Te electronic components, each of which is made up of a few
transistors, are called logic gates because they work on the principles
of boolean logic.
Logic gates
Te gates that you need to know about each have one or two inputs
and one output although this is not the case for all gates, some of which
may have many more inputs. Tere are four types of gates and they
are shown in Figure 19.4 on page 261. In addition to these four, there are
another 3 complementary gates which are formed by adding a NOT
gate to the output of the other three. Tese are called NAND, NOR
and XNOR and are ofen used in circuits.
It should be noted that the logic gates shown here are the ones used in
the HSC, but they are not the current standard gates. Te new gates
are shown in Figure 19.5 on page 261 for completeness so that if you
happen to see them in a newish book you’ll understand them. Te
cryptic symbols on them will make sense afer you fnd out exactly
what it is that a logic gate does.
as the number in normal binary representation,
but if the answer is negative, you may have to
convert it back to decimal.
If you have a two’s complement that you have
to convert, simply take the two’s complement of
the number, you’ll now have a positive integer,
convert that back to decimal and write a “-” in
front of it, it’s that simple.
Multiplication
Now things get a little more complicated, but
if you remember how to do long division from
primary school, it will be a lot simpler. Remem-
ber when you were given a problem like 342 ×
567, you would set it out and then multiply each
digit and shif to the lef (if you’ve forgotten, see
the sidebar). It’s similar with binary, but as you’ll
only ever be multiplying by 1, it’s even simpler.
If you’re given two binary numbers to multiply,
start by writing them one above the other. To
make it simpler for yourself, put the number
with the least 1s in it on the bottom
4
. Now work
through the bits in the lower number from right
to lef. If there is a 1 in the position, write the
number from the top line, but it shif it to the
lef so that its last digit is under the 1 in the top
number, continue this until you’ve gone through
all the bits in the lower number. Add up the
numbers you wrote down (being careful that
you don’t get the columns confused) and the
total is the answer.
In theory, if you are multiplying two 8-bit numbers than it is possible
for the answer to have sixteen bits, consequently you are unlikely to
have to multiply numbers which are too big because it’s simply too
long for a question worth one or two marks.
Division
Te last of the binary calculations you need to be able to do is division,
again if you remember how you used to do long division in primary
school you’ll fnd this fairly simple. You will usually be given a small
binary number (the divisor) to divide into a bigger one.
4 Tis isn’t strictly necessary, but it reduces the number of steps involved.
Calculate 57,, - 83,, in binary
Firstly convert the two numbers to their binary
representations.
57,, = 00111001¸
83,, = 01010011¸
-83,, = 10101101¸ as 2’s complement
Calculate 57,, + -83,,
0 0 1 1 1 0 0 1
1 0 1 0 1 1 0 1
1 1 1 1 carries
1 1 1 0 0 1 1 0 total
Te answer is negative (you can tell because the
number starts with a 1 and we’re using two’s com-
plement. So calculate it’s two’s complement before
converting back to decimal.
11100110
00011001 1’s complement
00011010 2’s complement
00011010¸ = 26 so the answer is -26.
Multiply 342 x 567 (a refresher)
342
567 ×
2394 multiply 342 by 7
20520 multiply 342 by 6 add a 0
171000 multiply 342 by 5 add 00
193914 add them up for the total
Multiply 11,, by 9,, in binary
Convert the two numbers to binary.
11,, = 1011¸
9,, = 1001¸
Put the 1001 on the bottom, it has the fewer 1s.
1011
1001 ×
1011 Te lefmost bit is a 1
1011000 3 zeros added to align
01100011 total
01100011¸ = 99,,
The software developer’s view of the hardware Electronic circuits to perform standard software operations
260 261 HSC Course
t NOT gates reverse their input, if the input is a 1, the output is a
0; and if the input is a 0 the output is a 1.
Tis might sound very simple, and it is, but don’t be fooled into think-
ing that it is not powerful, when combined in the correct way, these
four simple logic gates make your computer do pretty much anything.
Of course, there are many thousands of millions of them inside a
modern computer, which is why it appears so powerful.
Truth tables
Writing out what each gate does is pretty simple when you only have
the simple two input gates to deal with, but when arrangements get
more complex it can be dimcult to write out what a given arrange-
ment of gates will do as a sentence, so there’s a better way. Truth tables
are a simple way of setting out what a single gate or a whole array of
interconnected gates can do.
A truth table is simply a set of columns with one column represent-
ing each input and another set of columns representing the output (a
combination of gates may have more than one output). In addition if
you are working through a complex arrangements of gates, additional
columns might be put in the middle to make it a bit simpler to work
with. Te number of rows is determined by the number of inputs. As
you have to account for every possible combination of input values,
there will be 2 to the power of the number of inputs: 2 inputs = 4 rows,
3 inputs = 8 rows, 10 inputs = 2'" or 1024 rows (better hope there’s not
one of them in the HSC). Let’s look at the tables for the standard gates.
As you can see, if you look at the word descriptions earlier, the truth
tables tell you exactly the same thing, just in table form. Take some
time to make sure that you properly understand the tables as they
are they key to making and deciphering the more complex problems
that are coming up.
Filling in the input values is pretty easy if you remember the binary
system from before. When I make these tables I start at the top with all
zeros and then count in binary as I work down, that way I can be sure
that I haven’t missed any values, because if there are 3 inputs, and so 8
rows, the last number I should get to is 7, and if I’ve got 111 in the last
row for the input, then I know I’m probably right all the way through.
Figure 19.8 on page 264 shows a more complex circuit (one that we’ll
come back to later on). It has three inputs and two outputs and some
intermediate steps. Te intermediate steps make it easier to follow
what’s happening as you fll in the truth table. You still begin with fll-
ing in all the values for the inputs (8 sets in this case), then you work
through the intermediate steps and use them to get the fnal outputs.
Logic gates take binary input sig-
nals and produce a binary output
signal — just what value of this
output signal has is determined
by the values of the input signals
and the type of gate.
t AND gates have an output
of 1 if all of their inputs have a
value of 1, otherwise they output
0.
t OR gates have an output of
1 if any of their inputs is 1, they
will output 0 only if all their in-
puts are 0.
t XOR gates will output a 1
if only one of their inputs is 1, if
there are 0 or more than one input with a 1, then they output a 0.
101 10111010
Step 1: Write the two numbers down
and calculate the two’s complement
of the divisor (in this case it’s 011).
101 10111010
Step 3: Write the two’s complement of the
divisor below the bits you found, and do
the addition (which is really a subtrac-
tion) you can simply forget about any
overow bits. Write a 1 above the line.
101 10111010
011
000
1
Step 4: Copy digits down from the divi-
dend until you get a number at the
bottom that is bigger than the divisor. If
you don’t get a number bigger than the
divisor, write a 0 above the line.
101 10111010
011
000110
100
101 10111010
011
00011
10
101 10111010
011
0001
1

101 10111010
011
011
000110
011
110
1
100101
Repeat steps 3 and 4 until you run
out of digits in the dividend.
101 10111010
011
000110
011
1
1001
101 10111010
011
000110
011
11
1001
101 10111010
011
000110
011
110
10010
Step 5: When you get to the end you have
your answer, anything le over is the
remainder for the division. In this case the
nal answer is 100101 r 1 (or 37 r 1)
Step 2: Look along the dividend one bit
at a time starting from the le until you
get a binary number bigger than or
equal to the divisor.
Figure 19.2 - e binary division of 186 by 5.
Figure 19.4 - e four basic logic gates.
Note that the NOT gate is not always
shown with the triangle, if it is combined
AND OR
XOR NOT (Inverter)
Figure 19.6 - e complementary logic
gates.
NAND NOR
XNOR
Figure 19.5 - e four basic logic gates in
their new form.
AND OR
XOR NOT (Inverter)
& ≥1
=1 1
Figure 19.3 - A dierent type of OR gate.
The software developer’s view of the hardware Electronic circuits to perform standard software operations
262 263 HSC Course
This expression can be drawn as a series of
logic gates:
It’s not cheating to use three input gates, but it
is certainly a complex looking circuit for such
a seemingly simple task. If we were stuck with
using only two input gates, then the circuit
would have six AND gates, two OR gates and
three NOT gates. Surely there must be a way
of simplifying it. Of course there is.
Karnaugh maps
(a ∙ b ∙ c) + (a ∙ b ∙ c) + (a ∙ b ∙ c), the expression that describes what
it is we want to do is a maths expression, it uses Boolean operators
and there are mathematical ways of simplifying the expression down
to something easier to implement. Learning the mathematical way
is part of university maths, so we don’t need to learn that here, there
is a graphical method that is much simpler (at least in simple cases).
That method is by using a Karnaugh map, it’s named after Maurice
Karnaugh who developed ideas originally invented by Edward Veitch.
Karnaugh maps have a similar function to a truth table, but are arranged
in such a way that finding patterns is much simpler. Although you can
draw a Karnaugh map for any number of inputs, the most common
ones are 3 and 4 input maps — bigger than that and they really need
a computer to help with the pattern finding. The arrangements for 3
and 4 input Karnaugh maps are shown below.
It is important to note the major diference between these diagrams
and truth tables; whereas truth tables have their entries arranged in
numerical order, the bits in a Karnaugh map are arranged in a Gray
code
6
. With a Gray code any two values next to each other will only
be diferent by one bit — this is the key to getting a Karnaugh map to
work. To use the map you fll in the squares that correspond to the
inputs that give an output of 1 — don’t worry about the 0s.
When all the 1s are flled in there will be patterns either pairs
that run vertically or horizontally, or squares of 4. Tese
patterns are the key to simplifying things. In a traditional
Karnaugh map only these patterns count, but because we’re
allowed to use XOR gates pairs that form diagonally are
also important for our purposes. If we look at an invented
Karnaugh map, this will be clearer.
6 Named afer Frank Gray the man who patented the idea, he called it
“refected binary code”.
Circuit design steps
Te circuit in Figure 19.8 is a full adder, it takes two bits (I1
and I2) and a carry bit (C in) and works out the sum (S) of
the three bits and whether there is a carry to the next bit
(C out). Collections of these circuits are used to do all the
additions that go on in a CPU. Designing these circuits is
part of electrical engineering, but it’s also part of the HSC
course, and so here’s a brief overview of how designers go
about turning a digital problem into a solution containing
just the logic gates we know about so far. Tere’s a fair bit to
learn in this section, so take your time.
Te problem we will start with is a simple one. You have three
switches, each of which can either be on or of, you want an
output of 1 if exactly two of the switches are on, and an output
of 0 in every other case. Te frst step is to build a truth table
for the problem. In this case you use the description of the
problem to make the table.
You’ll notice that there are three cases where the output is
1, those are the ones that we will concentrate on. Te three
cases can be described as:
t Switch 1 of, Switch 2 on, Switch 3 on
t Switch 1 on, Switch 2 of, Switch 3 on
t Switch 1 on, Switch 2 on, Switch 3 of
Some special notation will make this simpler. Let’s call the
switches a, b and c. We also need some notation for our logic
gates, let’s use ∙ for AND and
+ for OR
5
, for NOT we’ll put a
bar over the letter so a means
NOT a. Tat means that we
can write the three state-
ments about the switches as:
ta ∙ b ∙ c
ta ∙ b ∙ c
ta ∙ b ∙ c
Tis can all be combined into
a single expression:
(a ∙ b ∙ c) + (a ∙ b ∙ c) + (a ∙ b ∙ c)
5 Yes, I realise it seems that + should mean AND, but there is a whole
branch of mathematics behind this, and in maths it makes more sense for +
to be OR and ∙ to be AND.
Table 19.3 - Truth tables for the four common
logic gates.
A B A AND B
0 0 0
0 1 0
1 0 0
1 1 1
A B A OR B
0 0 0
0 1 1
1 0 1
1 1 1
A B A XOR B
0 0 0
0 1 1
1 0 1
1 1 0
A NOT A
0 1
1 0
Switch 1 (a) Switch 2 (b) Switch 3 (c) Output
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 0
Figure 19.7 - A set of gates that will do what is required.
is arrangement though isn’t the most ecient, we must do
some further work to simplify it
Output
A
B
C
ab
c
00 01 11 10
1
0
1 1 1
1
ab
c
00 01 11 10
1
0
1 1 1
1
The software developer’s view of the hardware Electronic circuits to perform standard software operations
264 265 HSC Course
As you can see, the 1s can be grouped into pairs, as shown in the
right hand map. If we look at the horizontal group we can see that the
value of a is 0 in both cases, the value of c is 1 in both cases and the
value of b doesn’t matter, it can be either 0 or 1. So this group can be
represented as (c ∙ a) “c AND NOT a”. In the vertical pair, a is 1, b is 1
and c doesn’t matter, so that group can be written as (a ∙ b) “ a AND
b”. We’ve covered all the groups, so to work out the whole solution we
simply combine the groups with ORs, (c ∙ a) + (a ∙ b) “c AND NOT a
OR a AND b”.
If we do the same thing for our problem circuit we get the
following:
with diagonal pairs rather then horizontal or vertical ones. XORs
allow us to handle diagonal cases (the notation for XOR is ). In the
case of the lefmost diagonal pair, b is always 1 and a alternates with
c, so we can write this as (b ∙ (a c)) “b AND a XOR c”. For the other
diagonal a is always 1 and b alternates with c, this becomes (a ∙ (b
c)) “a AND b XOR c”. Combining the two parts with an OR we get (b
∙ (a c)) + (a ∙ (b c)).
Tis simplifed version doesn’t look a lot simpler than the original
version, it’s a bit shorter but looks more complicated. It’s when it gets
turned into a circuit diagram (Figure 19.10 on page 266) that the sim-
plifcation becomes clearer.
Speciality circuits
We have already seen one of the special circuits that is used inside
the CPU, the full adder, the circuit diagram for which is on page 264. A
simpler circuit which is also needed is the half adder, it takes two bits
and adds them to give a sum and a carry. One half adder is used at the
beginning of every multi-bit adder to handle the frst pair of bits as no
carry can come into that frst pair. You could probably design one with
the knowledge you already have from the earlier sections. Here’s the
description: the sum will be 1 if the two inputs have exactly one 1 in
them, the carry will be 1 if the two inputs are both 1. Te truth table
is shown in on page 266, and you’ll see pretty quickly from that, that the
Sum is just bit1 XOR bit2 and that the Carry is bit1 AND bit2. Te
circuit diagram is shown in Figure 19.11 on page 258.
To make a full 8-bit adder (or 16, 32 or any other number of bits) a
single half adder is used to add the two lowest value bits, and then
ab
c
00 01 11 10
1
0
1 1
1
ab
c
00 01 11 10
1
0
1 1
1
Figure 19.9 - Blank Karnaugh maps for 3 and 4 input
solutions.
Note that the labelling is not in numerical order but
in a Gray code so that only one bit changes between
one cell and any cell next to it.
ab
c
00 01 11 10
1
0
cd
ab
00 01 11 10
00
01
11
10
I1 I2 C in X
I1 AND I2
Y
I1 XOR I2
Z
Y AND C in
C out
X OR Z
S
Y XOR C in
0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 1
0 1 0 0 1 0 0 1
0 1 1 0 1 1 1 0
1 0 0 0 1 0 0 1
1 0 1 0 1 1 1 0
1 1 0 1 0 0 1 0
1 1 1 1 0 0 1 1
Table 19.4 - Truth table for the full adder circuit in Figure 19.8.
Figure 19.8 - A circuit for a full adder.
is circuit is one of the many that form part of the Arithmetic Logic Unit
in a CPU.
bit1
bit2
Carry
Carry
in
out
Sum
X
Y
Z
The software developer’s view of the hardware Electronic circuits to perform standard software operations
266 267 HSC Course
it’s carry and the next two higher order bits
go into the frst full adder - that adder’s carry
and the next two higer bits go into the second
full adder and so on, until the end. Te carry
from the fnal full adder shows that there was
an error in the calculation and that the result
it too large to ft in the integer.
One of the key components in modern com-
puters is a circuit known as a fip-fop. Flip-
fops, also known as bi-stable multivibrators,
are circuits which have two stable states and which can be made to
switch between them. Once a fip-fop is in a state it remains there
until it is told to change (or the power goes of). Tis makes them ideal
as a memory unit as they can be made to remember one bit of data.
Tere are a number of diferent types of fip-fops and they fnd difer-
ent uses throughout electronics and in computers. All have a few things
in common, one being that they have two outputs Q and Q which are
always the opposite of each other, by convention the Q output is the
main output and Q is the complementary output. We’ll start with the
simplest one. Te SR or Set-Reset fip-fop.
An SR fip-fop can be made from a pair of NOR gates arranged so the
the output of each gate is one of the inputs to the other gate - the other
two inputs are the S and R inputs. When both the S and R inputs have
a value of 0, nothing happens, Q keeps whatever value it has before. If
S is set to 1 while R remains at 0, Q has an output value of 1 regardless
of what its previous value was. When S returns to 0, Q will stay at 1.
If R is given the value 1 while S remains at 0, Q will have the value 0,
again regardless of what it had before, when R returns to
0, Q will remain with a value of 0. So you can see how the
fip-fop remembers what happened earlier.
You’re probably wondering what happens if both S and
R are given the value 1 at the same time. Tis is where
the multivibrator part of the name comes from, if both
S and R are 1 at the same time, the fip-fop enters a race
condition, with the value of Q and Q both dropping to
0, and consequently not remembering anything. Other
forms of fip-fop begin swapping quickly between 0 and
1 at high speed. Tis isn’t a problem, in fact
in some simple circuits a fip-fop arranged to
keep swapping is used to provide timing sig-
nals - it’s just not very useful as memory. All
fip-fops have a race condition, but in most
memory circuits additional circuitry is used
to make sure it never happens.
A variation on the SR fip-fop is the RS fip-fop
which is made from crossed NAND gates rather
than NOR gates. It works in the same way as the
SR fip-fop except that the active values of the S
and R inputs are reversed. When both S and R are
1 the circuit remembers, taking S to 0 sets Q to 1,
taking R to 0 sets Q to 0, and when they are both
0 the race condition occurs.
Tere are a number of more complex fip-fop
arrangements which are also used for memory
and other applications.
Like other boolean logic circuits fip-fops have
truth tables, but in this case they are slightly dif-
ferent because they have one state that is not
determined solely by the inputs, and another state
which is unstable, still you are expected to be able
to produce truth tables for the fip-fops. We’ll
work through the SR fip-fop here.
Start as you would for any other truth table, make a list of all the
possible input values (four of them). Ten work out the outputs for
the two middle states because they are completely determined by the
inputs. Remember that we are working with NOR gates which will
have a value of 1 if both inputs to them are 0 and 0 in all other cases.
So with R = 1 and S = 0, the output of the bottom NOR gate must be
0 (because one of it’s inputs is 1 and it doesn’t matter what the other
one is), so the input to the top NOR gate is 0 from the lower gate and
0 from the S input, so the top gate’s output must be 1.
If R = 1 and S = 0, this repeats. Te top gate must have an output of
0 because R = 1, the lower gate therefore has 0 at both inputs, and so
outputs 1.
bit1 bit2 Sum Carry
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1
Table 19.5 - Truth table for a half adder.
Figure 19.10 - e simplied circuit
Note that this contains just ve two-input gates which compares
with the four three-input gates or eleven two-input gates of the
rst solution.
Output
A
B
C
Figure 19.13 - An 8-bit adder
e adder is assembled from one half adder (position 0) and seven full adders.
B1 B2
Cin
Cout S
B1 B2
Cin
Cout S
B1 B2
Cin
Cout S
B1 B2
Cin
Cout S
B1 B2
Cin
Cout S
B1 B2
Cin
Cout S
B1 B2
Cin
Cout S
B1 B2
Cout S
1/2
0 1 2 3 4 5 6 7
Number 1
Number 2
Sum
Figure 19.12 - SR ip-op
is circuit uses a pair of crossed NOR gates.
S R Q Q
0 0 Previous Q Previous Q
0 1 1 0
1 0 0 1
1 1 0 (invalid) 0 (invalid)
Table 19.6 - Truth table for an SR ip-op
R
S
Q
Q
The software developer’s view of the hardware Programming of hardware devices
268 269 HSC Course
each bit and a few other wires to carry other signals. Serial commu-
nications sends one bit at a time and so serial cables have fewer wires
and the connectors are smaller.
You might think that parallel communication would be faster than
serial communications, and in the early days of computers, this was
correct, but it isn’t any longer. Te problem with parallel communica-
tions is that the signal in one wire can interfere with the signal in the
wire next to it, and the higher the frequency of the signals, the greater
the interference. Because serial cables carry only one signal in each
direction, the interference can be managed better and much higher
frequencies can be used, so bits can be sent faster. Additionally the
fastest transmission medium currently available, optical fbre, is con-
siderably easier to use as a serial medium than as a parallel medium
7
.
Input data streams
As bits arrive from a data stream what you see will depend upon
where you are programming. If you are high level programming you
will only see the fnalised data, your program will ask the device what
data is has every so ofen and then your program can do whatever it
needs. If you are programming this way you will need to make sure
that you read data before the operating system discards it, that means
your program will need to continually check on the state of the data.
A better way of handling incoming data in an application level pro-
gram is using call-backs. Most modern operating systems will provide
a call-back mechanism to programs running on it. To use a call back
you frstly write the function that will be used to process data when it
arrives, then you tell the operating system that when it has received
data from the device it should call your function. Ten your program
can go and do other things without worrying about checking on the
device, when data arrive your function will be called, it can then proc-
ess the data and your program can return to doing other things until
the function is called again. Tis method of handling data is the same
as we have seen for handling events.
When data are transmitted using a serial protocol they are broken
down into bits by hardware and then transmitted over the wire (or
radio link) and reassembled in hardware at the far end. It’s not as sim-
ple as just sending the bits one afer another, there are other signals
and bits that have to be included to make the system work. When
you put the system, the transmission information, the connectors to
be used, the type of cabling all together you get a protocol. Tere are
many protocols used in computer systems, one you may be familiar
7 Optical fbre can be used as a parallel medium by using a set of lasers
of diferent frequencies to encode diferent bits. Tis is dimcult to arrange as
it requires very precise optical alignments.
In the case of S = 0 and R = 0 the top NOR gates
output will be determined by the output of the
lower gate, if the lower gate’s output is 1, the top
gate will output 0, and that 0 will mean that the
lower gate has 0 on both inputs, and hence it will
continue to output 1 - this is the memory state.
Te circuit will continue to output whatever was
there before.
In the case of S = 1 and R = 1 then the top will
output 0, so the bottom NOR gate will put out
0 and the input to the top will 1 and 0 so it will
output a 0 and both Q and Q will show 0 outputs
which is invalid.
Programming of hardware
devices
Tere is a large market for add-ons to computers, or peripherals if you
prefer the more technical term. Printers, scanners, external hard drives,
keyboards, mice and many other devices are sold to plug into com-
puters. Unlike the motherboard and other parts inside the computer,
where a manufacturer can control the exact hardware specifcations,
these peripherals are designed to be used with a variety of diferent
computers and in many cases with a variety of operating systems.
From a programmer’s point of view, this range of possible devices is
either a goo thing, or a bad thing, it depends upon exactly what it is
you are developing. If you are developing applications sofware, then
the range is a good thing, if you are programming on any of the main
operating systems, there are programming interfaces available that
let you ignore the specifcs of a device and just print, or read a cursor
position, or play a video to the display. You will not have to worry
about how the device works, or in some cases even whether it exists,
the operating system will take care of it for you.
If, on the other hand, you fnd yourself working outside the main
operating systems, or your job is working with a specialised device
which doesn’t have operating system support (or you fnd yourself
working for a device manufacturer) then you need to understand how
it is that computers communicate with external devices.
Tere are two forms of communication used by computers, parallel
and serial. With parallel communication multiple bits of information
are sent at the same time, usually in groups of 8 bits when the device
is outside of the computer. Parallel cables have an individual wire for
Figure 19.14 - R S
ip-op
is circuit uses a pair of crossed NAND gates.
S R Q Q
0 0 1 (invalid) 1 (invalid)
0 1 1 0
1 0 0 1
1 1 Previous Q Previous Q
Table 19.7 - Truth table for an RS ip-op
R
S
Q
Q
The software developer’s view of the hardware Programming of hardware devices
270 271 HSC Course
the conversation. If you hear
“goodbye” from the person
at the other end, you know
that they have fnished the
conversation, if they just
stopped talking and hung
up, then you wouldn’t know
if they had fnished or the
line had dropped out. Te
stop bit is like the goodbye.
One is added to the end of
a data transmission so that
the receiver knows that any 0s at the end of the data were meant and
weren’t the result of the signal dropping out.
In the case of both start and stop bits, they are added to the beginning
or end of the whole data stream that is being transmitted, not before
and afer each byte.
Parity and error correction
Communications can be dodgy, especially when you are using a serial
system where data can be lost or subject to interference. If you are
talking to someone and their message doesn’t get through to you
properly, what you hear won’t make sense to you and you can ask them
to repeat it, but as computer data is meaningless 0s and 1s, then there
is no way a computer could know that data was corrupt until it tried
to work on it. Terefore a system is needed so that the computer (or
at least the communications electronics) can work out if something
has gone wrong and ask for a correction.
Te simplest system, and the most widely used is called parity. Parity
simply takes a byte of data and counts the number of bits that have the
value 1. If there is an odd number of 1s it adds another 1 to the end
of the data, if there is an even number of 1s it adds a 0. Tis is called
“even parity”. Tat means that if you count up the number of 1s in a
byte with even parity, there will always be an even number of them.
When data are being transmitted, the only thing that can go wrong is
that a 1 turns into a 0, or a 0 into a 1. If you are using even parity and
one of the bits gets fipped, then there will be an odd number of 1s
and you’ll know you have an error. If you get an error, you can ask for
the data to be resent, and keep asking until it comes through correctly.
You’ve probably noticed a problem though, if two bits got fipped, then
you’d be back to an even number of 1s and you wouldn’t notice the
error. For that reason we say that parity can detect one error. Whether
this is acceptable will depend on how reliable the data transmission
with is Universal Serial Bus (USB) protocol which has become a very
popular way of connecting devices (almost replacing all the others).
By complying with this protocol devices made by one manufacturer
should work with devices made by another manufacturer.
As programmers we need not concern ourselves with the electrical and
mechanical parts of a protocol, but it is possible that you will have to
work with the data parts. Any data sent using a serial protocol have
extra bits added to overcome some problems associated with serial
transmission:
t Start bits
t Stop bits
t Parity bits
t Error correction bits
Te actual data bytes are sent one afer another, until they have all
been sent, or until a predefned number of bytes has been sent, then
the transmission is ended. If there is still more data to be sent then
an new transmission is started and this is repeated until all the data
have been sent.
Start bits
Data bits are encoded in a transmission as either a signal or no signal,
so when a 1 arrives it is easily recognised because there is something
to detect. A 0 on the other hand is more dimcult because there is no
signal, so hwo do you tell the diference between a 0 and just nothing
happening. Well if it is between two 1s, then it’s simple, the signal will
drop to nothing, then go back up again. What if, however, the 0 is the
frst bit in the data, how would you know that it had arrived? Tat’s
where a start bit comes in.
A start bit is a 1 that is added to the start of the transmission of data. It
doesn’t matter if the data starts with a 1 or a 0 it is always added. Te
1 that is sent will alert the receiver that more bits are about to arrive
and to start noticing them so that they can be made into bytes. Te
system discards the 1 before doing any conversion, of course. Some-
times multiple start bits are used, to give the circuitry at the far end
a chance to wake up, but with modern circuits this now uncommon.
Stop bits
Stop bits are added to the end of data so that the receiver knows that
the link is still active and didn’t unexpectedly drop out. Te situation
stop bits try to address is familiar to anyone who uses a mobile phone.
When you’re having a conversation and the line drops out it can take
a couple of seconds for you to realise that the person on the other
end is no longer then. Stop bits are like the “goodbye” at the end of
~
1 1 1 1 1 1 0 0 0 0
Start bit Stop bit
Parity bit (0)
~ ~ ~
Data (0110110)
Figure 19.15 - Start, stop and parity bits
is piece of data is being transmitted with 1 start bit, one stop bit and even parity.
The software developer’s view of the hardware Programming of hardware devices
272 273 HSC Course
as the craf only recorded about 15 minutes worth of information. Te
use of a Reed-Solomon (255, 223) code meant that errors introduced
by the signal travelling over 4,500 million km to Earth could be cor-
rected and the images and other data successfully decoded.
When there is likely to be less of a problem with interference, but
you still want to allow for the fact that there might be errors, then
less intensive methods of error detection can be used. One of the
more common systems is the Cyclic Redundancy Check or CRC.
CRC works by performing mathematical operations on each byte of
a block of data, usually 256 to 1024 bytes and then passing along the
results of its check.
As the data arrive at the receiver, it performs the same calculations
on the arriving data, it then checks its result with the CRC data sent
by the sender. If the two values are the same, the data is considered
alright, if there is a diference, a request is made to resend the entire
block of data. Tis process is repeated until all of the data have been
received successfully.
Clearly the CRC method of doing things is very emcient if the prob-
ability of an error is low. On a bad transmission medium it can be
very inemcient because an error of just 1 bit in 1024 bytes can cause
the entire block to be resent.
Processing data streams
Processing data when they arrive is no more dimcult than packaging
it up to be sent in the frst place. Clearly you have to have know the
protocol that is being used so you can make sense of all the bits, but
once you know whether start and stop bits are being used, and what
sort of parity is being used (if any) then the process is fairly straight
forward.
Begin by identifying the start and stop bits if they are being used,
and remove them from the data stream. Remember, if the stream has
multiple bytes in it, the start and stop bits only occur at the beginning
and end of the whole stream, they are not attached to each byte.
Te next step is to divide the data up into byte sized pieces. Each piece
will contain the number of bits the protocol specifes and the parity
bit if one is used. Check each byte for correct parity if it is being used,
if they are correct, cross out the parity bits. What you are lef with is
the transmitted data. How that data will be interpreted is, of course,
up to the program that uses it - the same data could be text, part of an
mp3 fle, pixels in an image or pretty much anything else - it all gets
transmitted and received the same way.
system is. If errors are rare and so the chances of two errors in the same
byte is very small, then parity is fne. Some computers use memory
that has in-built parity so that memory errors can be easily detected.
Of course nothing is free, and the cost of using parity is that the amount
of information you transmit is greater than if you didn’t worry about
error detection. When parity was frst used it was added to 7-bit ASCII
code, so there was an extra 1 bit added for every 7 transmitted, so
that’s a 14% increase in data transmission. One of the trade-ofs in
system design is the loss of speed in exchange for more reliable data
transmission.
Odd parity also exists, in this case the total number of 1s in a byte plus
the parity bit will be odd rather than even. Odd parity is less commonly
used than even mainly for historical reasons, it has exactly the same
advantages and disadvantages as even parity.
Tere are two main problems with parity, it’s ability to only detect a
single error, and that you can’t fx that error except by having the data
retransmitted. Tere are many real-world systems where these limita-
tions are critical to success and so other error systems must be used.
One of the code systems that avoids some of the problems of parity
is the Hamming code system. Te Hamming system, which is named
afer its inventor Richard Hamming, allows you to detect two errors
and correct one error in any given data package.
Te exact mathematics involved in making, checking and correcting
Hamming codes are not complex, and can easily be built into elec-
tronics, although they are beyond the scope of the SDD course. By
constructing the codes in diferent ways, longer sets of data can be
encoded and checked. Te simplest version is the (7, 4) code where 7
bits are used to encode 4 bits of data (the other 3 are the error system
bits) which means you have an increase in size of 75% in the data
stream. Other versions are a bit more emcient, such as the (19, 15)
code where 19 bits are used to send 15 bits of data, a 27% increase.
Hamming codes are not the only ones used for error correction and
detection, another system is known as Reed-Solomon codes, afer its
inventors, and one real world case shows how important these codes
can be. In 1977 the United States launched Voyager I and II on jour-
neys to Jupiter and Saturn to take colour photographs and record lots
of other data. By cleverly adjusting the path Voyager II took around
Saturn it was possible to send it on to both Uranus and Neptune, the
two outermost planets in the solar system.
By the time Voyager II got to Neptune in 1989 signals from the space-
craf took four and a half hours to reach Earth, so if there were any
problems with the data there was no way for them to be retransmitted
The software developer’s view of the hardware Programming of hardware devices
274 275 HSC Course
When it comes to programming the frst thing is to make sure that
the data you are sending will be in the correct format, that is has the
correct start and stop bits and parity, and that it will be sent at the
right speed. Tese are normally just settings that you include in your
program when you set up the serial communications controller.
To control the device you need to add any required header information.
Header information is ofen required to set the device up, or to select
from a set of options that a device might have. Ofen you will need to
do this even if the device is primarily used for input. For example if
you are using a barcode scanner, some units require data, including
header information, set to it to tell it what barcode systems it should
read or ignore, or how long to wait afer a successful read to ensure
that the same barcode isn’t read multiple times.
Header information may need to include information about the data
that are to follow it. It may be necessary for your program to collect
all the data and store it so it can calculate the header information
such as the number of bytes in the data, or perhaps error detection
information. Once your program has collected all it needs, header,
data and trailing information it can then pass it to the hardware that
will actually control the transmission of the data.
Control systems
Embedded controllers have become a common addition to many
devices. One of the reasons that ovens and washing machines have
become so much more complex is that they no longer have to rely on
electrical and mechanical devices to control them, instead an embed-
ded controller can do the work. Controllers are simple single chip
devices that contain a CPU, some memory and a little bit of input and
output circuitry. Programs can be written that are then loaded onto
memory on the controller. Whenever the controller starts up it will
automatically begin running the installed sofware.
Originally these embedded controller chips were programmed directly
in machine language, and still, that is all that can be stored on the chip,
but now there are programming environments that allow a developer
to work in a high level language such as C or C++ and have the machine
code loaded onto the controller.
Controller chips typically have only limited capabilities, yet clever
programming can make them do quite complex operations. Tese
do, however, normally break down into just two diferent types of
operations, either sensing or commanding.
Controller chips will be connected to a sensor, or an array of sensors
which let them know about what is going on. Tese sensors may be
Once the raw data gets to the program it will
have to process it further. Tere may be header
data to check and remove, there might be a need
to store anything received until all the parts of
the transmission have been received. If a com-
plex error detection system is being used then
the received data may need to be checked as a
block.
Te header information might modify the mean-
ing of the transmitted data, and so that needs to
be taken into account. For example an mp3 fle
might contain an album cover picture in addi-
tion to the music. Te header data would include
information about where the cover information
is within the fle so that it can be turned into a
picture rather than a sound.
Processing the data might also obligate your
program to respond in some way so that the
transmitting program knows that the data were
received correctly. For example, a good video
message program will expect a reply from the
receiver telling it how well the data are being
received so that it can adjust the speed of data
transmission if information is being delayed
unacceptably or lost.
Generating output to an appropriate
device
If you fnd yourself working with a device for which the manufacturer
hasn’t provided drivers, or you’re working for a device manufacturer,
you might fnd yourself needed to produce output which targets a
specifc device, rather than a generic one. If you are working with a
specifc device, the manufacturer will normally supply a manual which
specifes what commands are needed for what functions, and how the
device expects those commands to be packaged.
Tis ofen happens when you are working on a system where special-
ised hardware has been developed for a specifc purpose. For example
you could be working on a system which reads the barcode on a ticket
and then opens an entrance gate if the ticket is valid. While barcode
readers are quite common, and the manufacturer would normally
supply the interface code you’d need - the gate system might be built
by another section of your company and simply uses a serial interface
to connect to the controlling computer. You’ll just get the command
list and protocol instructions.
Decoding data
Te following stream of data is received.
1000011000101101100010001
Te protocol uses one start bit, one stop bit and even
parity, the data are three 7-bit integers. You want to
work out if the data are correct and what the values are.
Begin by removing the start and stop bits, this leaves
000001100010110110001000
Because we know that the data are 7-bit integers with a
parity bit, we divide this data into groups of 8.
00000110 00101101 10001000
Now check that the data are valid (that there is an even
number of 1s in each byte).
2 × 1, 4 × 1, 2 × 1 so all the data are valid. Te next step
is to remove the parity bits
0000011 0010110 1000100
Convert these back to decimal numbers
3, 22, 68
The software developer’s view of the hardware Programming of hardware devices
276 277 HSC Course
Te last bastion of these type of printers are the small receipt print-
ers that some shops use - but even these are ofen controlled by page
description languages. So were you to fnd yourself writing point-of-
sale sofware for low-end systems, you might need to write code for
one of these printers. Control of these devices is simple, because the
devices have fairly limited capabilities. Typical options for this type of
printer, apart from printing characters, let you advance paper, change
the colour of the ribbon being used for the printing, cut the paper, or
switch modes to print very simple graphics or characters from other
languages.
Typically all these types of printers work with 8-bit ASCII codes, using
the standard codes for printing Roman and other European language
codes - as far as I have been able to tell, none of these printers works
with Unicode characters. Changing modes is controlled by sending
control codes which are values from 0-31, the non-printing characters
in ASCII.
Most of the control codes are standard, for example the code 0D,,
causes the print head to return to the lef hand side to start printing
again; code 0A,, causes the paper to advance one line so that the
printing will be on a new line. Combining the two makes the printer
begin printing at the beginning of a new line. Other codes can make
the printer’s bell ring 07,, or 09,, will make the printer skip to the next
tab stop. Table 19.8 shows the all 32 control codes, not all of which
would be used with a printer.
Tere are a number of codes that are specifcally for device control,
and what each will do is determined by the printer that is being used.
Ofen these codes are followed by standard ASCII values to add infor-
mation. For example on an Epson U220 receipt printer, the sequence
1B 70 30 19 FA,, will cause a cash drawer attached to the printer to
pop open. Te 1B,, frst character is the escape character and tells the
printer that the codes following aren’t letter codes, but are part of the
command. Using an escape sequence such as this is a very common
printer control technique.
Specialist devices
If you are working as a programmer in many industries you may have
to program devices that are specifc to that industry and consequently
aren’t supplied with all the programming tools that are available for
things like printers or hard disk drives. Tis isn’t quite as bad as it seems
though because although the device might be unique the components
with which it is built are likely to be fairly standard. In particular it
would be unusual for even a highly specialised piece of equipment to
not use one of the standard methods of interfacing with a computer,
serial or parallel communications, or increasingly USB. Te reason is
buttons on the front of the washing machine, a thermometer that
senses the temperature of an oven, or an encoder that determines the
position of a motor - or pretty much anything else that can give out
a digital value. Sensors that don’t have a direct digital value will be
connected to an analog to digital converter (ADC) which converts the
measurement to a digital value.
On the output side a controller chip will be connected to display
devices of some type, maybe a simple 7 segment LED or maybe a more
complex screen. Te output might also be passed to an actuator, which
is any device which causes something to move. Simple actuators are
electric motors which turn while power is applied and stop otherwise,
electromagnetic latches such as those on some security doors. Some
devices can’t take a digital value to control them, in those cases a
digital to analog converter (DAC) is used to convert the digital value
to an analog voltage.
Te programming in most controllers is fairly straight forward. Te
controller monitors the input signals, usually by using a loop to read
each value. Te programming integrates all the inputs to determine if
something needs to be done. It then determines whether or not any val-
ues need to be sent to the output devices and sends them if necessary.
Ofen a feedback system will be used where some of the inputs directly
monitor the output devices and provide feedback on what is happen-
ing. Motors, in particular, can be dimcult to control, and so feedback
is usually necessary. When you apply some power to a motor for a
particular length of time, it won’t always turn the same amount, the
load on the motor may have changed, it might be overloaded and so
it doesn’t move the expected amount. By putting an encoder on the
motor which turns its motion into numbers, the controller can moni-
tor what the motor is doing and adjust its output further if necessary.
Specialised motors called stepper motors can be used to simplify this
process as they include an encoder and monitor themselves, so a con-
troller can instruct a stepper motor to move a certain amount and it
will - the controller need not monitor the process.
Printer operation
In the past, printers were noisy mechanical devices that printed one
character at a time, and one line afer another. Modern printers are
considerably more sophisticated than their predecessors, and are now
usually controlled by sending a fle that describes how the page is
to be printed, the processor in the printer then translates that into
instructions that the print engine uses to produce the page. Te HSC,
however, expects you to know how to program printers that are largely
no longer made, and certainly would not be seriously considered in
any new system.
Code Function
00 Nothing
01 Start of heading
02 Start of text
03 End of text
04 End of transmission
05 Enquiry
06 Acknowledge
07 Ring bell
08 Backspace
09 Tab
0A Start new line
0B Vertical tab
0C Start new page
0D Carriage return
0E Shi in
0F Shi out
10 Data link escape
11 Device specic
12 Device specic
13 Device specic
14 Device specic
15 Negative acknowledge
16 Idle
17 End of block
18 Cancel
19 End of paper
1A Substitute
1B Escape
1C File separator
1D Group separator
1E Record separator
1F Unit separator
Table 19.8 - ASCII control codes.
The software developer’s view of the hardware Programming of hardware devices
278 279 HSC Course
Exercises
Worked solutions to these exercises can be found beginning on page 299.
1. Convert these decimal integers to their binary representations. In
each case make the binary number 8-bits long, and in the case of
negative integers, use the 2s complement representation.
a. 231
b. -74
c. 4
d. -81
2. Convert the following 8-bit positive binary integers to their deci-
mal representations.
a. 01101100
b. 10101010
c. 00110111
d. 11010101
3. Convert the following 8-bit 2’s complement binary numbers to
their decimal representations.
a. 01101100
b. 10101010
c. 00110111
d. 11010101
4. Convert these numbers from their decimal to their binary
representations.
a. 217.3175
b. -6.97214
c. 0.0031789
d. -0.0001765
5. Convert the following 32-bit fractions to their decimal equivalents.
Tese numbers are in IEEE 754-2008 format.
a.
b.
6. Perform the following additions using binary numbers.
a. 23 + 19
b. 87 + 52
c. 54 + 17
d. 19 + 189
7. Perform the following subtractions using binary numbers, if the
answer is negative leave the result in 2s complement form.
simple, integrated circuits which handle all the protocol and transfer
are easily and cheaply available, so unless there is some very compel-
ling reason, the cheap and easy solution is the way to go.
Te program you write will probably just have to use the available
protocol to read data from the various sensors in the device and send
data to the displays, and actuators - with, of course, some processing
in between. Te nice part is that the communications all turns out to
be simple data transfer, it doesn’t matter whether the devices at the
end are the massive electric motors that drive the axes of a 4 metre
astronomical telescope or a 7 segment LED counting down time on
a washing machine, to a programmer it will just be a stream of data
formatted according to a protocol designed as part of the device.
Generally you will be supplied with a description of the protocol the
data uses from the engineers who built it, detailing how it will present
data at the interface, or what format a command takes to have it send
the data. Any special commands the device needs or that it may send
and how to send it the data it needs to perform a task. Most of our work
is likely to be involved with the programming away from the interface.
Increasingly other devices that don’t look like a conventional desktop
or laptop computer have a computer style interface for programmers
to use. Devices such as mobile phones and games consoles provide
programming environments which are similar to those seen on the
more conventional machines, along with some additional limitations.
The software developer’s view of the hardware Programming of hardware devices
280 281 HSC Course
a. 53 - 29
b. 29 - 53
c. 87 - 112
d. 47 - 94

but not other numbers. and hence the one used by C#. So ASCII got extended from 7-bits to 8-bits and called ‘Extended ASCII’ although most people just say ‘ASCII’ now. At the time of writing Unicode supports over 100. started each string with an integer which counted the number of characters. but ine cient. Unicode is a system that is used to encode all characters in all written languages. Finishing with a terminating value is a little easier to program. Other systems were invented by other computer manufacturers.000 different characters and symbols used in languages and dialects all over the world. the rst representations of text were made to match the Roman alphabet used in those countries. to Representation of data within the computer Everything in the computer. A particular collection of bits could be a number representing a bank balance. but in modern languages. and many of their languages had 1 American Standard Code for Information Interchange Integer representation Everyone knows that computers work with numbers. and on storage media is stored as binary codes in transistors within the silicon making up the computer’s circuitry. even if your program continues to show only English instructions. then you should be supporting Unicode in your programs as it means users around the world can input data in their local languages. Representing sentences and longer sequences of characters in the computer is simply a matter of setting enough memory aside to hold all the characters. so as computers became more common. ASCII is still there in the rst part of the UTF-8 encoding. a 0. which is quite a common programming technique. you need about 96 di erent codes to cover everything. and much more e ciently if you are going to make strings up by adding bits together. Because computers were originally developed in countries where English was the dominant language. Character representation Computer systems store text. but ASCII won and now all computers use it. lots and lots of text. C# adds a StringBuilder class to the language which works di erently. One of the rst improvements made to microprocessors was the 2 http://unicode. Example — Convert 87 binary 87 ÷ 2 = 43 r 1 43 ÷ 2 = 21 r 1 21 ÷ 2 = 10 r 1 10 ÷ 2 = 5 r 0 5÷2=2r1 2÷2=1r0 1÷2=0r1 Writing the remainders from the bottom to the top = 1010111 so: 87 = 1010111 If you were asked for an 8-bit number. is to put a terminating value. extending to have characters for hieroglyphics. What is important to realise right from the beginning is that the bits of data have no inherent meaning at all they are just stored electrical signals. part of an mp3 music le. Using seven binary bits in a row gives you 128 di erent possible combinations. Keep this principle in mind and you won’ t be confused when you realise that 00111000 is both the letter ‘H’ and the number 56. a colour record. the meaning comes from the way so ware and hardware interprets that data. but you really could call them anything you wanted — we’ll stick to the 1 and 0 convention. when microprocessors rst came out. If the string is long. is meant that Pascal format strings are limited to 255 characters. Of course it wasn’t long before people outside of Europe mentioned that they’d like to use computers too. Important text such as books like this and unimportant text like spam emails. cuneiform. pixels in an image — it will all depend on what the other so ware (which is itself just a collection of bits) does with the data. up to 32-bits are used to extend the system. Something else was needed and so Unicode was born. All up. ere are two ways of marking a string so that the so ware knows how long the string is. the 48 letters of the Greek alphabet and a few extra symbols. they worked with integers. Normally we write these as 1s or 0s. musical notations used in the Byzantine era. there is little need to worry about this as the string functions built into the language will just do the job as needed. Unicode has gone even further than just modern languages. this is quite time consuming. When microprocessors were rst introduced this wasn’t 100% true. 10 digits and a couple of dozen punctuation characters. not everyone speaks English. is system was formalised as the ASCII system (now called the 7-bit ASCII code). so this length was chosen.The software developer’s view of the hardware Representation of data within the computer considerably more characters than you could t into a scheme that allowed 256. simply add a 0 to the le of the number. and even imaginary fonts such as Klingon and Elvish (although they’re not o cial). you can add as many zeroes as needed without it changing the value of the number — just as 0134 and 134 are the same number. and then removes the old string. notably EBCDIC by IBM. there was a push to include more characters so people speaking other European languages could type words such as ‘façade’ without having to go back with a pen to add accents to the letters.org/ 248 HSC Course 249 . e C method. as the last character in the string. If you are writing so ware. Of course. e extra characters from 128 to 255 cover all the accented letters in most European languages. which was used by FORTRAN and COBOL and many other languages but isn’t used much any more. the rst 32 codes (0-31) were used for controlling printers and the last 96 (32-127) were used for all the printable characters. e Pascal system. In most languages whenever you add something to a string the computer actually copies the old string with the change made. e only thing you need to really know about strings as they e ect programming is that they are necessary. to get them to work with fractions took considerable low level programming. that way a string can potentially be as long as is needed. English uses 52 letters (26 upper case and 26 lower case).

128 (you don’t have to remember them. Repeat steps 1 and 2 until you reach 0 as the number to divide. the method explained here isn’t the fastest. divide it by 2 and leave the remainder. Which of them actually means a negative binary number is up to the operating system and the programming language. it’s just quicker to use fewer bits. it can deal with negative integers too. that means that if you are using an integer system that includes negative numbers your possible range changes. Again. Other manufacturers put the highest value byte rst and then the progressively lower ones a er that — these are the big endians. Add up the remaining numbers and the result is the decimal equivalent. 128 0 64 1 32 0 16 1 8 0 4 1 2 1 1 1 CPUs have a ‘natural’ integer size. there are a number of ways of doing this. Start by writing. 4. For the rest of this section (and in the HSC itself) we’re going to limit ourselves to 8-bit integers. Start with a decimal number. Numbers in English are generally big endian. at number is the binary equivalent of the decimal number. e obvious question about all of this is how useful is it in everyday programming — to be perfectly honest. Let’s start with integers though. One of the important things you need to be able to do with binary numbers is to convert them to and from decimal numbers . these are a few easy marks in the exam. so you don’t have to worry. a size that is built into them. but there will be questions about this in the HSC. 250 HSC Course 251 . a part that could handle fractions in calculations. each number is just double the one to the right. Endian-ness is is one of those things that professional programmers probably don’t have to worry about any more. Endian-ness only becomes a problem when data is transferred from a computer using one system to a computer using the other. Add up the remaining numbers e rst readily available CPUs 64 + 16 + 4 + 2 + 1 = 87 used 8-bits in their calculations. It’s a pretty easy process once you’ve done it a few times. but it is the easiest. 3. You’ll need to able to convert back too — from binary numbers to decimal numbers. although sometimes a poet will insist on being contrary and having “four and twenty blackbirds baked in a pie”.The software developer’s view of the hardware Example — Convert 01010111 to decimal 128 0 64 1 32 0 16 1 8 0 4 1 2 1 1 1 addition of a oating point unit. there was no consensus between CPU manufacturers as to which byte of a multibyte integer should go rst. they used 32-bits for integers. 1. An integer is a whole number. e rst thing to know about binary numbers is that they still use the same number of bits as a positive number. 4. if you’re working with positives. and fairly easy to learn. 1. so numbers 0 to 4 294 967 295 were possible. is doesn’t matter. We already know that if we have 8-bit positive binary numbers. Positive integers are not the only integers a computer deals with. we say “two hundred and y eight”. 64. then the available range of numbers is from 0 to 255. you 16-bit processors that replaced can check your answers are correct when doing the exam. 2. e is shows one of the advantages of this section of the course. Again. 27. then the higher value bytes in order a er that — these are the little endians. Some manufacturers put the lowest value byte in the lowest memory position. So practice. all the techniques we look at with 8-bit integers are exactly the same for any other implementations. 1. Representation of data within the computer now to make it easier. e only possible complication is that in the HSC examination you’re not allowed to use a calculator. Binary is based on 2. 3. Although everyone agrees how to turn a decimal number into a binary number. them could handle a range of 0 to 65  535. Cross out any number that has a 0 under it. that way you’ll be prepared for the HSC. All modern programming languages look a er all of this for you. so you’ll have to do the dividing (and the multiplication that comes later) in your head — so don’t start using a calculator 3 Decimal numbers are just those that you’re used to using every day. Write the binary number with one digit under each of the numbers you wrote in step 1. 2. -3876 are all integers 2 ½ isn’t. 16. the one here is just one particularly simple way. When computers became really popular for people at home. 8. Write all the remainders in order starting with the last one and working to the rst one. Again. if you’re working with negatives. 01010111 = 87 as we would expect from the earlier example. Divide your answer from step 1 by 2 and again leave the remainder. not very useful at all. so you need to know it for that. 64-bit processors are in most new computers meaning positive integers from 0 to 18 446 744 073 709 551 615 can be easily used inside programs. If we are using negative numbers. then the range is -128 to +127 (or -127 to +127 depending on the scheme). one that you could use to count the number of people on a bus. then you can only use positives that are within the range permitted. then you have to use all positives. 32. 4. 2. but it’s useful to know. with modern programming languages all this is taken care of for you. so special measures are taken in this circumstance to avoid problems. Of course you can’t mix positive and negative representations and expect them to work. they are called decimal because they are based on 10. tive integers from 0 to 255. so they could represent posiSo. and as this book is being written. While there is a simple correspondence between positive binary numbers and decimal numbers (it comes from simple arithmetic) there isn’t a correspondingly simple one for negative numbers — in fact there are three di erent common methods of representing negative integers in the computer. do all these examples and exercises without. this is fairly simple once you practice a couple of times. Cross out the numbers above the 0s. ere are a number of ways to do this. from right to le 1.

1 . Otherwise. and add 1. It is important to note that both 00000000 and 10000000 represent zero but the second version is generally considered an error. you’d use two’s complement because it’s the only one that works. We’ll cover adding 1 later in this chapter. if the sign bit is 1 then the rest of the number is negative. Note again that both 00000000 and 11111111 represent zero. Binary digits Hexadecimal Binary digits Hexadecimal Each of the four components digit digit of a colour represents 8 bits of information and so o en that 0000 0 1000 8 is represented as a pair of hexa0001 1 1001 9 decimal digits. all colours are 24 bit when displayed. Negative numbers using one’s complement e next form of negative number is the one’s complement. so the examples now will be simple ones.2 . If you’re working in any modern computing language all that is hidden by the implementation of the language on the computer. On a screen. and this one is now much more widely used. a 0010 2 1010 A 50% transparent light blue colour would have components A 0011 3 1011 B = 80 R = A0 G = B0 B = 0100 4 1100 C FF and would be written out 0101 5 1101 D as 80A0B0FF or more likely as 0x80A0B0FF (the 0x at the start is 0110 6 1110 E the standard way of representing 0111 7 1111 F a hexadecimal number in C# and other programming languages).Binary to octal and octal used because there are only 10 distinct digits in the Hindu-Arabic we to binary conversion table. Negative numbers using two’s complement e third form of negative numbers is the two’s complement form and you’re probably wondering why there’s yet another form. it uses the digits from 0 to 7 each of which represents 3 bits in the binary number.The software developer’s view of the hardware Negative numbers using sign bits e simplest form of negative number is simply to use the le most bit (also called the most signi cant bit) as a sign bit. So. HSC Course 253 252 . starting from the right. and it will always be a 1 for negative numbers. Hexadecimal. To convert a number from binary to octal start by breaking the binary number into groups of three. use and you need 16 digits for hexadecimal). 87 = 01010111 so the one’s complement is 10101000 if we add 1 to that we get 10101001 and that’s the two’s complement. but hexadecimal is still used in modern computing. and then add 1 to it. So. then add one or two 0s to the le . If this bit is 0 then the rest of the number is positive. the twos complement of +87 is as you would expect 01010111 — it’s only the negative numbers that change. e other system used. is form of negative number is the one that you have to use to do calculations. 2 or 3 zeros to the le most group if it doesn’t already contain 4 bits. 111 7 is the hexadecimal system (also referred to as the hex system). On of the big improvements in computers over the past 20 years has been their ability to display a wide range of colours on the screen. e original IBM personal computers could display 16 colours. Notice that the most signi cant bit in the -87 representation is a 1. To make a two’s complement number. All this might seem very theoretical. 32 bits are ARGB colours — the di erence that the A part of a 32 bit colour can be used to represent the transparency of a colour when combining images. To someone used to dealing with Table 19. which we’ll see later on. 01010111 = 87 so 10101000 = -87 . with three representations which do you choose? If you were being forced to do binary arithmetic. 24 bits are called RGB colours. you break the binary number up starting at the right. If the rst group doesn’t have three binary digits in it. It’s important to note that with each of these representations of negative numbers. it’s part of the number it just acts like a sign bit. the second version although correct is considered an error in most systems. We know that 01010111 is 87. or base 16 breaks the binary number into groups of 4 digits and then represents them using the digits 0-9 and A-F (A to F are Table 19. All modern computers can handle millions of colours. For example. One of the common places it turns up is in the representation of colour data. Octal is the base 8 numbering system. you rstly make a one’s complement. being able to see the 4 table. ere are two common ones.Binary to hexadecimal and hexadecimal to binary conversion colours. for example. Other representations Representation of data within the computer Binary digits 000 001 010 011 100 101 110 Octal digit 0 1 2 3 4 5 6 Writing all those 1s and 0s becomes pretty tedious so there are other ways of representing binary data. and you need to know both for the HSC. the rst colour Macintoshs could handle 256. To specify a colour either 24 or 32 bits are used. it doesn’t matter. To make a one’s complement number you simply swap all the 1s for 0s and 0s for 1s. but it’s not a sign bit. the positive numbers don’t change. Again. so 11010111 is -87 if we are using sign bits.

To make the representation used by the CPU you need to do the following. To convert the fractional part.010110001111111110 57. 254 HSC Course 255 .The software developer’s view of the hardware Example — Convert 01010111 to octal 01010111 becomes 001 010 111 when we break it into 3s and add a 0 to the beginning. We don’t need to add any 0s to the le most group as it already contains 4 digits. 4. the . in real life. in this case 10000100 . you’ll get 127. ere is a standard for the use and implementation of oating point numbers in computers.34765 = .56240 × 2 = 1. 0101 0111 becomes 57 . in C# they are available as the and types.12480 × 2 = 0. 11. Fractions are more properly called oating-point numbers because a fraction implies one number divided by another while a oating-point just means that the number has a decimal point somewhere and so also includes irrational numbers such as e and pi. Write the 8 bits of the exponent + 127. Repeat step 3 until you have a total of 24 binary digits.49920 × 2 = 0. If the number you started with was greater than 1. Either by using the table provided or by calculating in your head. 96-bits and 128-bits.69530 0.35160 though it is the same number. it’s not di cult.89760 × 2 = 1. Example — Convert 01010111 to hexadecimal 01010111 becomes 0101 0111 when we break it into 4s.94880 × 2 = 1.034765 = 111001.18080 0. these conversions might put you o programming as a career. Floating points are used throughout so ware.’ and then the binary fraction.18080 × 2 = 0. Convert the integer part in the same way as before. it’s called IEEE 754-2008. 2.34765 to binary 57 ÷ 2 = 28 r 1 28 ÷ 2 = 14 r 0 14 ÷ 2 = 7 r 0 7÷2=3r1 3÷2=1r1 1÷2=0r1 0. count the number of spaces you moved it. the 8 exponent bits and then the 23 mantissa bits.89760 0. including the digits you got from the conversion of the integer part. convert each group to the octal digit. C# also has a xed-point representation called that is used for currency calculations where the rounding that happens in oating point numbers isn’t allowed. Representation of data within the computer Example — Convert 57. 10.59040 × 2 = 1. 1. there’s no way of storing that dot. Add 127 to the exponent. and then discard it if it was a 1. Representation fractions of Integers aren’t the only type numbers that your so ware will use. 1 for negative).24960 0. that it starts with — this means you are only writing down the fractional part of that number.49920 0. convert each group to the hexadecimal digit. Split the number into it’s two halves. Write the integer part.99360 × 2 = 1. 001 010 111 becomes 127 components like that means that they will know that there’s lots of blue.12480 0.98720 0. but rest assured. e rst step is converting a decimal number with digits to the right of the decimal point into it’s binary representation.56240 0.99840 × 2 = 1. e number that is le (the one that starts with 1.010110001111111110 Move the binary point to the le 5 positions to get: 1. followed by a binary point ‘. We’ll look at the IEEE 32-bit system. 64-bits. e 32 bit number you now have is the binary representation of the fraction.98720 × 2 = 1. the right and le sides of the decimal point.11001010110001111111110 × 2 (or 10 in binary) e 23 bits to the right of the binary point become the mantissa. and there are worked answers for them on page 299. Either by using the table provided or by calculating in your head. it’s just 01000010011001010110001111111110 that there are a lot of steps and you need to practice it a few times to get the hang of it. so only use them if you have to. a 1 of it was negative. Note.59040 0. Write the 23 bits of the mantissa leaving o the 1. however it’s not the representation used by the computer — it couldn’t be.78120 × 2 = 1. very few programmers ever need to do this (in fact many would have no idea how to go about it). again count the number of places you moved it. you’ll get a number less than 127 — and if it was between 1 and two. Let’s start with the number 57. at means if your original number was bigger than 2 you’ll get a number bigger than 127. fractions are important too. Start with a sign bit. It has four recommended implementations a 32-bits. Simple. 6. 9. 57 = 111001 0.37485.97440 × 2 = 1. is is the true binary representation of the number.99360 0. If the original number was less than 1. 7.69530 × 2 = 1. move the binary point to the le until there is just a 1 to it’s le .99680 × 2 = 1.24960 × 2 = 0. ere are some exercises on page 279 that you can try. Now it’s just a matter of writing out the bits.79520 × 2 = 1. Now.97440 0.34765 × 2 = 0. e whole number is then bundled into a 32-bit form starting with a sign bit (0 for positive.39060 × 2 = 0. 8. Write the integer portion of the result down.79520 0. double the fraction. If this number was written out as decimal it would be 2 158 014 719 and that doesn’t convey anywhere near the same amount of information even 5. if the original number was less than 1. the move the binary point to the right until there is a 1 to its le . 3.39060 0. e 101 of the exponent is added to 01111111 (127 ) to make the exponent part of the number.) is called the mantissa. this number is called the exponent. but this time that number is negative. isn’t it. a bit less green and red and so the resultant colour will be a light blue. Convert the exponent + 127 into a binary number. Floating point numbers are handled inside the processor by the oating point unit (FPU) which is designed to work quickly with these types of numbers. doesn’t go anywhere.99840 0. Actually. the 1 to the le is dropped.99680 0. 12. put a 0 if the original number was positive. in this case.78120 0.94880 0. pretty much the only time you are ever going to need to do these is for the HSC exam. Even with such help though oating-point numbers are much slower to use than integers.

e only thing you need to be careful about is that you use the correct version of a negative binary number. you’re probably going to think that like oating point conversions. so there are only four possible ways they can add up: 0+0=0 0+1=1 1+0=1 1 + 1 = 10 (that’s 0 with 1 carried over) Now. a er all. 00110101 01101000 11 10011101 carries total If you convert this back to a decimal number you get 157 which is the correct answer. If you’re adding 8-bit bytes. as you are going to need some of the techniques you learned there. this is material you’ll need to know for the HSC and not otherwise. multiplication and division. the HSC syllabus doesn’t specify that you have to. by extension you can do any number of bits). you don’t write this extra bit down. 256 . Especially if you have time during an exam. but in the CPU it would cause an over ow error which may or may not be handled gracefully by the operating system. it’s a good habit to convert the answer back to decimal to check if you got it correct. and possibly a carry from a previous column — this is just like addition from primary school. it’s just a matter of adding each pair of bits from the bytes. However. Of course you’re expected to be able to add more than just two binary digits.The software developer’s view of the hardware Now. e standard includes representations up to 128 bits. If you’re adding with a carry. ere are four basic operations you are expected to do with binary numbers: addition. now if the answer is positive then this is not a problem because the two’s complement of a positive number is exactly the same HSC Course 257 Add 53 to 104 Firstly convert both numbers to their binary representations 53 = 104 = 00110101 01101000 Binary arithmetic Everyone knows that computers are good at doing calculations. As you’d know from maths. there’s no single digit that represents the sum. and possibly haven’t used since. it’s the same for binary numbers. so it’s not surprising that as a programmer you are expected to know at least the fundamentals of binary arithmetic. And just a reminder. so there’s no 2. Addition Addition is pretty straightforward. Subtraction e good news is. just that you recognise the representations. you already know everything you need to know to do subtraction. you’re not allowed to use a calculator in the HSC exam. you might think that the next thing to learn would be how to convert these fractions back to decimal numbers.1 . e HSC tends to ask for 8 bit or smaller calculations. generally you’re going to be marked on the working and steps in solving the problem. it’s a really bad idea to cheat and work out the answer in decimal and then convert back. is doesn’t matter on paper. You get the same situation as when you add 5 + 5 in decimal. add the pairs together with carries as needed. Exponent 127 + exponent value Sign bit 0 for +ve 1 for -ve Fraction Figure 19. Whenever you do a binary calculation. If you’re really interested in how to go about it.e IEEE 754-2008 representation of a oating point binary number in 32-bit format. Incidentally. but remember. I’ve included the method in “Converting oating point numbers back to decimal” on page 283. and it’s pretty obvious if you don’t do the steps. just put it on the le and make a 9-bit number. Representation of data within the computer e rst three are as you’d expect (I hope) it’s only the last one that might look confusing. this is binary. you should be able to handle the addition of 8-bit bytes (and if you can do them. going further doesn’t prove anything more. e other forms or negative can’t be used for calculations. When you do the subtraction it is possible that you will get an overow from the last bit to the 9th bit — unlike for addition. there are only two digits to worry about. It will help if you can remember how you used to do arithmetic in primary school. not on getting the nal answer. you just forget about it. so you write 0 and carry 1 to the next column to the le . subtracting is the same as adding a negative number. you can check if you got the marks. One of the advantages of having 32 and 64-bit processors is that they can handle much larger numbers without over owing. so don’t use one here. you have to use the two’s complement negative (from page 252). e other thing to remember is that the answer to a subtraction will be in two’s complement form. that is. subtraction. you know how to make a negative binary number and you know how to do addition. Now. If you get to the end and still have a 1 to carry. but surprisingly some of this can be useful in real computing — especially the boolean logic later in this chapter. as you’d expect. then it is possible to get 1 + 1 + 1 which equals 1 with a 1 carried over.

57 = 00111001 83 = 01010011 -83 = 10101101 as 2’s complement Calculate 57 + -83 00111001 10101101 111 1 carries 1 1 1 0 0 1 1 0 total e answer is negative (you can tell because the number starts with a 1 and we’re using two’s complement. Division e last of the binary calculations you need to be able to do is division. e points to remember are that when you do the subtraction of the divisor (by adding the two’s complement) just do the number of digits necessary and you can drop any over ow bits. 11 = 1011 9 = 1001 Put the 1001 on the bottom. You will usually be given a small binary number (the divisor) to divide into a bigger one. there are another 3 complementary gates which are formed by adding a NOT gate to the output of the other three. If there is a 1 in the position. it will be a lot simpler. some of which may have many more inputs. In theory. write the number from the top line. Figure 19. It’s similar with binary. In addition to these four.83 in binary Firstly convert the two numbers to their binary representations.The software developer’s view of the hardware Calculate 57 . ut they do need some practice until you get the hang of them. you may have to convert it back to decimal. is as always to convert the numbers to binary representations. e electronic components. but if the answer is negative. 1011 1001 × 1011 1011000 01100011 01100011 = 99 e le most bit is a 1 3 zeros added to align total 1’s complement 2’s complement Electronic circuits to perform standard software operations Clearly there must be some electronic way of doing all of these arithmetic and other operations. If you’re given two binary numbers to multiply. but if you remember how to do long division from primary school.5 on page 261 for completeness so that if you happen to see them in a newish book you’ll understand them. It’s also helpful if you can do simple binary to decimal conversions in your head (up to 4 bits is enough). it has the fewer 1s. Remember when you were given a problem like 342 × 567. 4 is isn’t strictly necessary. To make it simpler for yourself. see the sidebar). and to calculate the two’s complement of the divisor — you’re going to need it for the subtractions. but it shi it to the le so that its last digit is under the 1 in the top number. Multiply 11 by 9 in binary Convert the two numbers to binary. If you have a two’s complement that you have to convert. 11100110 00011001 00011010 as the number in normal binary representation. you’ll now have a positive integer. put the number with the least 1s in it on the bottom4.4 on page 261. ese are called NAND. None of these calculations are di cult. simply take the two’s complement of the number. It should be noted that the logic gates shown here are the ones used in the HSC. consequently you are unlikely to have to multiply numbers which are too big because it’s simply too long for a question worth one or two marks. but they are not the current standard gates. but it reduces the number of steps involved. continue this until you’ve gone through all the bits in the lower number. So calculate it’s two’s complement before converting back to decimal. are called logic gates because they work on the principles of boolean logic. Multiplication Now things get a little more complicated. NOR and XNOR and are o en used in circuits. start by writing them one above the other. 00011010 = 26 so the answer is -26. Now work through the bits in the lower number from right to le . it’s that simple. Electronic circuits to perform standard software operations e rst step. because computers are electronic devices. e cryptic symbols on them will make sense a er you nd out exactly what it is that a logic gate does. so there are plenty of exercises at the end of the chapter with worked solutions in the back. e new gates are shown in Figure 19. ere are four types of gates and they are shown in Figure 19. again if you remember how you used to do long division in primary school you’ll nd this fairly simple. it’s even simpler. surprisingly though there are just a few very simple devices that do the work. convert that back to decimal and write a “-” in front of it. 258 HSC Course 259 .2 on page 260 shows the steps in a binary division. if you are multiplying two 8-bit numbers than it is possible for the answer to have sixteen bits. each of which is made up of a few transistors. you would set it out and then multiply each digit and shi to the le (if you’ve forgotten. but as you’ll only ever be multiplying by 1. Multiply 342 x 567 (a refresher) 342 567 × 2394 20520 171000 193914 multiply 342 by 7 multiply 342 by 6 add a 0 multiply 342 by 5 add 00 add them up for the total Logic gates e gates that you need to know about each have one or two inputs and one output although this is not the case for all gates. Add up the numbers you wrote down (being careful that you don’t get the columns confused) and the total is the answer.

which is why it appears so powerful. 101 10111010 Step 1: Write the two numbers down and calculate the two’s complement of the divisor (in this case it’s 011). You still begin with lling in all the values for the inputs (8 sets in this case). but don’t be fooled into thinking that it is not powerful. Note that the NOT gate is not always shown with the triangle. Logic gates take binary input signals and produce a binary output signal — just what value of this output signal has is determined by the values of the input signals and the type of gate. then you work through the intermediate steps and use them to get the nal outputs. the last number I should get to is 7.6 gates. XNOR Figure 19. Of course. if the input is a 1. A truth table is simply a set of columns with one column representing each input and another set of columns representing the output (a combination of gates may have more than one output).5 . XOR gates will output a 1 if only one of their inputs is 1. Figure 19. Figure 19. when combined in the correct way. It has three inputs and two outputs and some intermediate steps. is might sound very simple. anything le over is the remainder for the division. 10 inputs = 2 or 1024 rows (better hope there’s not one of them in the HSC). and if I’ve got 111 in the last row for the input. Write a 1 above the line. if you look at the word descriptions earlier. and do the addition (which is really a subtraction) you can simply forget about any over ow bits.e four basic logic gates in their new form. 1 101 10111010 011 000 Step 3: Write the two’s complement of the divisor below the bits you found. then they output a 0. the truth tables tell you exactly the same thing. 101 10111010 Step 2: Look along the dividend one bit at a time starting from the le until you get a binary number bigger than or equal to the divisor. AND gates have an output of 1 if all of their inputs have a value of 1. 3 inputs = 8 rows. Figure 19.2 - e binary division of 186 by 5. 100101 101 10111010 011 000110 011 110 011 1 Step 5: When you get to the end you have your answer. if it is combined NAND NOR 1001 1001 10010 101 10111010 101 10111010 101 10111010 011 011 011 000110 000110 000110 011 011 011 1 11 110 Repeat steps 3 and 4 until you run out of digits in the dividend. OR gates have an output of 1 if any of their inputs is 1. that way I can be sure that I haven’t missed any values. e complementary logic & AND =1 XOR ≥1 OR 1 NOT (Inverter) Figure 19. As you can see. just in table form. so there’s a better way. Take some time to make sure that you properly understand the tables as they are they key to making and deciphering the more complex problems that are coming up. 260 HSC Course 261 .A di erent type of OR gate. these four simple logic gates make your computer do pretty much anything. Truth tables are a simple way of setting out what a single gate or a whole array of interconnected gates can do. they will output 0 only if all their inputs are 0. Figure 19. but when arrangements get more complex it can be di cult to write out what a given arrangement of gates will do as a sentence. additional columns might be put in the middle to make it a bit simpler to work with. In addition if you are working through a complex arrangements of gates.The software developer’s view of the hardware Electronic circuits to perform standard software operations NOT gates reverse their input. e intermediate steps make it easier to follow what’s happening as you ll in the truth table. otherwise they output 0.8 on page 264 shows a more complex circuit (one that we’ll come back to later on). there will be 2 to the power of the number of inputs: 2 inputs = 4 rows.4 . Let’s look at the tables for the standard gates. there are many thousands of millions of them inside a modern computer.e four basic logic gates. and if the input is a 0 the output is a 1. 1 10 100 101 10111010 101 10111010 101 10111010 011 011 011 0001 00011 000110 Step 4: Copy digits down from the dividend until you get a number at the bottom that is bigger than the divisor. In this case the nal answer is 100101 r 1 (or 37 r 1) AND OR XOR NOT (Inverter) Truth tables Writing out what each gate does is pretty simple when you only have the simple two input gates to deal with. As you have to account for every possible combination of input values. the output is a 0. if there are 0 or more than one input with a 1. then I know I’m probably right all the way through. and so 8 rows. If you don’t get a number bigger than the divisor.3 . Filling in the input values is pretty easy if you remember the binary system from before. and it is. e number of rows is determined by the number of inputs. write a 0 above the line. because if there are 3 inputs. When I make these tables I start at the top with all zeros and then count in binary as I work down.

but it is certainly a complex looking circuit for such a seemingly simple task. this will be clearer. We also need some notation for our logic gates. at means that we can write the three state1 0 ments about the switches as: 0 0 A B Output C Figure 19. but are arranged in such a way that finding patterns is much simpler. In a traditional Karnaugh map only these patterns count. When all the 1s are lled in there will be patterns either pairs that run vertically or horizontally. let’s use ∙ for AND and + for OR5. The arrangements for 3 and 4 input Karnaugh maps are shown below. Although you can draw a Karnaugh map for any number of inputs. Designing these circuits is part of electrical engineering. I realise it seems that + should mean AND. so we don’t need to learn that here. but because we’re allowed to use XOR gates pairs that form diagonally are also important for our purposes.A set of gates that will do what is required. b and c. Of course there is. You’ll notice that there are three cases where the output is 1. those are the ones that we will concentrate on. Switch 3 on Switch 1 on. he called it “re ected binary code”. e three cases can be described as: Switch 1 o . Switch 2 o . You have three switches. it’s named after Maurice Karnaugh who developed ideas originally invented by Edward Veitch. there is a graphical method that is much simpler (at least in simple cases). With a Gray code any two values next to each other will only be di erent by one bit — this is the key to getting a Karnaugh map to work. ab c 00 01 11 10 1 0 1 1 1 1 ab c 00 01 11 10 1 0 1 1 1 1 Table 19.7 . the bits in a Karnaugh map are arranged in a Gray code6. Collections of these circuits are used to do all the additions that go on in a CPU. it takes two bits (I1 and I2) and a carry bit (C in) and works out the sum (S) of the three bits and whether there is a carry to the next bit (C out). Switch 2 on. you want an output of 1 if exactly two of the switches are on.The software developer’s view of the hardware A 0 0 1 1 A 0 0 1 1 A 0 0 1 1 A 0 1 B 0 1 0 1 B 0 1 0 1 B 0 1 0 1 NOT A 1 0 A AND B 0 0 0 1 A OR B 0 1 1 1 A XOR B 0 1 1 0 Electronic circuits to perform standard software operations This expression can be drawn as a series of logic gates: It’s not cheating to use three input gates. e rst step is to build a truth table for the problem. then the circuit would have six AND gates. and so here’s a brief overview of how designers go about turning a digital problem into a solution containing just the logic gates we know about so far. is arrangement though isn’t the most e cient.Truth tables for the four common logic gates. it uses Boolean operators and there are mathematical ways of simplifying the expression down to something easier to implement. That method is by using a Karnaugh map. If we were stuck with using only two input gates. Switch 2 on. e problem we will start with is a simple one. whereas truth tables have their entries arranged in numerical order. but there is a whole branch of mathematics behind this. Switch 3 o Some special notation will make this simpler. Switch 3 on Switch 1 on. each of which can either be on or o . Karnaugh maps have a similar function to a truth table. 262 HSC Course 263 . To use the map you ll in the squares that correspond to the inputs that give an output of 1 — don’t worry about the 0s. It is important to note the major di erence between these diagrams and truth tables. or squares of 4.3 . the expression that describes what it is we want to do is a maths expression. the most common ones are 3 and 4 input maps — bigger than that and they really need a computer to help with the pattern finding. and an output of 0 in every other case. Let’s call the switches a. Learning the mathematical way is part of university maths. If we look at an invented Karnaugh map. 6 Named a er Frank Gray the man who patented the idea. and in maths it makes more sense for + to be OR and ∙ to be AND. Switch 1 (a) 0 0 0 0 1 1 1 1 Switch 2 (b) 0 0 1 1 0 0 1 1 1 0 1 0 1 1 0 1 1 0 a∙b∙c a∙b∙c a∙b∙c is can all be combined into a single expression: (a ∙ b ∙ c) + (a ∙ b ∙ c) + (a ∙ b ∙ c) 5 Yes. Circuit design steps e circuit in Figure 19. for NOT we’ll put a Switch 3 (c) Output bar over the letter so a means 0 0 NOT a.8 is a full adder. ese patterns are the key to simplifying things. ere’s a fair bit to learn in this section. so take your time. two OR gates and three NOT gates. but it’s also part of the HSC course. In this case you use the description of the problem to make the table. we must do some further work to simplify it Karnaugh maps (a ∙ b ∙ c) + (a ∙ b ∙ c) + (a ∙ b ∙ c). Surely there must be a way of simplifying it.

4 .8. it can be either 0 or 1.9 . I1 I2 C in X I1 AND I2 Y Z C out X OR Z 0 0 0 1 0 1 1 1 S Y XOR C in 0 1 1 0 1 0 0 1 with diagonal pairs rather then horizontal or vertical ones. One half adder is used at the beginning of every multi-bit adder to handle the rst pair of bits as no carry can come into that rst pair. Combining the two parts with an OR we get (b ∙ (a c)) + (a ∙ (b c)).Blank Karnaugh maps for 3 and 4 input solutions. a is 1. b is always 1 and a alternates with c. the value of c is 1 in both cases and the value of b doesn’t matter. To make a full 8-bit adder (or 16. that the Sum is just bit1 XOR bit2 and that the Carry is bit1 AND bit2. it takes two bits and adds them to give a sum and a carry. You could probably design one with the knowledge you already have from the earlier sections. so that group can be written as (a ∙ b) “ a AND b”. is simpli ed version doesn’t look a lot simpler than the original version. it’s a bit shorter but looks more complicated. A simpler circuit which is also needed is the half adder.8 . so to work out the whole solution we simply combine the groups with ORs. So this group can be represented as (c ∙ a) “c AND NOT a”. and you’ll see pretty quickly from that. is circuit is one of the many that form part of the Arithmetic Logic Unit in a CPU. For the other diagonal a is always 1 and b alternates with c. e truth table is shown in on page 266. b is 1 and c doesn’t matter. If we do the same thing for our problem circuit we get the following: ab c 00 01 11 10 1 0 1 1 1 ab c 00 01 11 10 1 0 1 1 1 Figure 19. and then Figure 19.A circuit for a full adder. the 1s can be grouped into pairs. the circuit diagram for which is on page 264. ab c 00 01 11 10 0 1 ab cd 00 01 11 10 00 01 11 10 Speciality circuits We have already seen one of the special circuits that is used inside the CPU.The software developer’s view of the hardware bit1 bit2 X Z Y Carry in Sum Carryout Electronic circuits to perform standard software operations As you can see. this becomes (a ∙ (b c)) “a AND b XOR c”. We’ve covered all the groups. the full adder. Note that the labelling is not in numerical order but in a Gray code so that only one bit changes between one cell and any cell next to it. It’s when it gets turned into a circuit diagram (Figure 19. (c ∙ a) + (a ∙ b) “c AND NOT a OR a AND b”. 32 or any other number of bits) a single half adder is used to add the two lowest value bits. In the case of the le most diagonal pair. In the vertical pair. Here’s the description: the sum will be 1 if the two inputs have exactly one 1 in them. I1 XOR I2 Y AND C in 0 0 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 1 1 Table 19. as shown in the right hand map. XORs allow us to handle diagonal cases (the notation for XOR is ).Truth table for the full adder circuit in Figure 19. If we look at the horizontal group we can see that the value of a is 0 in both cases. e circuit diagram is shown in Figure 19.10 on page 266) that the simpli cation becomes clearer. so we can write this as (b ∙ (a c)) “b AND a XOR c”. the carry will be 1 if the two inputs are both 1. 264 HSC Course 265 .11 on page 258.

0 0 0 1 You’re probably wondering what happens if both S and R are given the value 1 at the same time.that adder’s carry and the next two higer bits go into the second full adder and so on. Like other boolean logic circuits ip.Truth table for a half adder.The software developer’s view of the hardware A B C Figure 19.op arranged to keep swapping is used to provide timing signals . Q keeps whatever value it has before. taking R to 0 sets Q to 0. Other forms of ip. until the end. so the top gate’s output must be 1.An 8-bit adder e adder is assembled from one half adder (position 0) and seven full adders.6 . nothing happens.ops have a race condition. e carry from the nal full adder shows that there was an error in the calculation and that the result it too large to t in the integer. Flipops. and another state which is unstable. HSC Course 267 Table 19. An SR ip. ere are a number of di erent types of ip.op enters a race condition. Remember that we are working with NOR gates which will have a value of 1 if both inputs to them are 0 and 0 in all other cases. When S returns to 0. make a list of all the possible input values (four of them).op.op remembers what happened earlier. S 0 0 1 1 R 0 1 0 1 Q Previous Q 1 0 0 (invalid) Q Previous Q 0 1 0 (invalid) Table 19. It works in the same way as the SR ip. so the input to the top NOR gate is 0 from the lower gate and 0 from the S input. 7 6 5 4 3 2 1 0 Sum Figure 19. So you can see how the ip. en work out the outputs for the two middle states because they are completely determined by the inputs. also known as bi-stable multivibrators. taking S to 0 sets Q to 1. When both the S and R inputs have a value of 0. e top gate must have an output of 0 because R = 1. When both S and R are 1 the circuit remembers. when R returns to Carry 0.op except that the active values of the S and R inputs are reversed. Number 1 Number 2 B1 B2 Cin Cout S B1 B2 Cin Cout S B1 B2 Cin Cout S B1 B2 Cin Cout S B1 B2 Cin Cout S B1 B2 Cin Cout S B1 B2 Cin Cout S B1 B2 1/2 Cout S Output One of the key components in modern computers is a circuit known as a ip. and consequently not remembering anything. If R = 1 and S = 0.5 . still you are expected to be able to produce truth tables for the ip.ops. Q will stay at 1.13 . We’ll start with the simplest one. ere are a number of more complex ip.op. is isn’t a problem.12 . with the value of Q and Q both dropping to 0. All ip.op is the RS ip.op can be made from a pair of NOR gates arranged so the the output of each gate is one of the inputs to the other gate .op begin swapping quickly between 0 and 1 at high speed. If R is given the value 1 while S remains at 0. Electronic circuits to perform standard software operations it’s carry and the next two higher order bits go into the rst full adder . is makes them ideal as a memory unit as they can be made to remember one bit of data.op arrangements which are also used for memory and other applications. but in most memory circuits additional circuitry is used to make sure it never happens. Q will remain with a value of 0. Q has an output value of 1 regardless of what its previous value was. Q will have the value 0. All have a few things in common. this repeats. if both S and R are 1 at the same time. the output of the bottom NOR gate must be 0 (because one of it’s inputs is 1 and it doesn’t matter what the other one is). We’ll work through the SR ip.SR ip. If S is set to 1 while R remains at 0.op is circuit uses a pair of crossed NOR gates.op here. is is where the multivibrator part of the name comes from. one being that they have two outputs Q and Q which are always the opposite of each other. are circuits which have two stable states and which can be made to switch between them. Once a ip. and so outputs 1. the ip. in fact in some simple circuits a ip.e simpli ed circuit Note that this contains just ve two-input gates which compares with the four three-input gates or eleven two-input gates of the rst solution.ops have truth tables.Truth table for an SR ip. the lower gate therefore has 0 at both inputs.the other two inputs are the S and R inputs.op is in a state it remains there until it is told to change (or the power goes o ).op which is made from crossed NAND gates rather than NOR gates. A variation on the SR ip.op bit1 0 0 1 1 bit2 0 1 0 1 Sum 0 1 1 0 Start as you would for any other truth table.ops and they nd di erent uses throughout electronics and in computers. R Q S Q Figure 19.it’s just not very useful as memory. again regardless of what it had before.10 . So with R = 1 and S = 0. but in this case they are slightly different because they have one state that is not determined solely by the inputs. e SR or Set-Reset ip. by convention the Q output is the main output and Q is the complementary output. and when they are both 0 the race condition occurs. 266 .

When you put the system. each bit and a few other wires to carry other signals. and hence it will continue to output 1 . or play a video to the display. When data are transmitted using a serial protocol they are broken down into bits by hardware and then transmitted over the wire (or radio link) and reassembled in hardware at the far end. If you are programming this way you will need to make sure that you read data before the operating system discards it. and the higher the frequency of the signals. there are other signals and bits that have to be included to make the system work. or in some cases even whether it exists.7 . It’s not as simple as just sending the bits one a er another. From a programmer’s point of view. or read a cursor position. e circuit will continue to output whatever was there before. the connectors to be used. that means your program will need to continually check on the state of the data. this was correct. these peripherals are designed to be used with a variety of di erent computers and in many cases with a variety of operating systems.The software developer’s view of the hardware R Q In the case of S = 0 and R = 0 the top NOR gates output will be determined by the output of the lower gate. the interference can be managed better and much higher frequencies can be used. the top gate will output 0. ere are two forms of communication used by computers. the transmission information.Truth table for an RS ip. when data arrive your function will be called. Programming of hardware devices S Figure 19. so bits can be sent faster. If you are high level programming you will only see the nalised data. and that 0 will mean that the lower gate has 0 on both inputs. Most modern operating systems will provide a call-back mechanism to programs running on it. then you tell the operating system that when it has received data from the device it should call your function.this is the memory state. it depends upon exactly what it is you are developing. or your job is working with a specialised device which doesn’t have operating system support (or you nd yourself working for a device manufacturer) then you need to understand how it is that computers communicate with external devices. on the other hand. ere are many protocols used in computer systems. A better way of handling incoming data in an application level program is using call-backs. so the bottom NOR gate will put out 0 and the input to the top will 1 and 0 so it will output a 0 and both Q and Q will show 0 outputs which is invalid. there are programming interfaces available that let you ignore the speci cs of a device and just print. is method of handling data is the same as we have seen for handling events.R S ip. usually in groups of 8 bits when the device is outside of the computer. the type of cabling all together you get a protocol. You will not have to worry about how the device works. You might think that parallel communication would be faster than serial communications. the operating system will take care of it for you. In the case of S = 1 and R = 1 then the top will output 0. external hard drives. then the range is a good thing. Q S 0 0 1 1 R 0 1 0 1 Q 1 (invalid) 1 0 Previous Q Q 1 (invalid) 0 1 Previous Q Table 19. parallel and serial.op is circuit uses a pair of crossed NAND gates. scanners.op Programming of hardware devices Input data streams As bits arrive from a data stream what you see will depend upon where you are programming. mice and many other devices are sold to plug into computers. but it isn’t any longer.14 . To use a call back you rstly write the function that will be used to process data when it arrives. your program will ask the device what data is has every so o en and then your program can do whatever it needs. ere is a large market for add-ons to computers. optical bre. the greater the interference. and in the early days of computers. e problem with parallel communications is that the signal in one wire can interfere with the signal in the wire next to it. where a manufacturer can control the exact hardware speci cations. you nd yourself working outside the main operating systems. or peripherals if you prefer the more technical term. if you are programming on any of the main operating systems. if the lower gate’s output is 1. or a bad thing. If. is is di cult to arrange as it requires very precise optical alignments. Parallel cables have an individual wire for 268 HSC Course 269 . Unlike the motherboard and other parts inside the computer. this range of possible devices is either a goo thing. With parallel communication multiple bits of information are sent at the same time. Serial communications sends one bit at a time and so serial cables have fewer wires and the connectors are smaller. If you are developing applications so ware. en your program can go and do other things without worrying about checking on the device. keyboards. it can then process the data and your program can return to doing other things until the function is called again. Additionally the fastest transmission medium currently available. is considerably easier to use as a serial medium than as a parallel medium7. Printers. one you may be familiar 7 Optical bre can be used as a parallel medium by using a set of lasers of di erent frequencies to encode di erent bits. Because serial cables carry only one signal in each direction.

Parity and error correction Communications can be dodgy. Start bits Data bits are encoded in a transmission as either a signal or no signal. then you’d be back to an even number of 1s and you wouldn’t notice the error. Well if it is between two 1s. If there is still more data to be sent then an new transmission is started and this is repeated until all the data have been sent. not before and a er each byte. Stop bits are like the “goodbye” at the end of 270 Programming of hardware devices the conversation. you know that they have nished the ~ ~ ~ ~ 1 conversation. When you’re having a conversation and the line drops out it can take a couple of seconds for you to realise that the person on the other end is no longer then. You’ve probably noticed a problem though. the signal will drop to nothing. the only thing that can go wrong is that a 1 turns into a 0. or until a prede ned number of bytes has been sent. they are added to the beginning or end of the whole data stream that is being transmitted. Figure 19. then go back up again. if they just 0 1 1 0 1 1 0 0 1 stopped talking and hung Stop bit Start bit up. e system discards the 1 before doing any conversion. For that reason we say that parity can detect one error. e 1 that is sent will alert the receiver that more bits are about to arrive and to start noticing them so that they can be made into bytes.15 . then you wouldn’t know Parity bit (0) if they had nished or the line had dropped out. Sometimes multiple start bits are used. e simplest system. A 0 on the other hand is more di cult because there is no signal. then it’s simple. one stop bit and even parity. e stop bit is like the goodbye. If there is an odd number of 1s it adds another 1 to the end of the data. One is added to the end of a data transmission so that the receiver knows that any 0s at the end of the data were meant and weren’t the result of the signal dropping out. If you hear Data (0110110) “goodbye” from the person at the other end. Any data sent using a serial protocol have extra bits added to overcome some problems associated with serial transmission: Start bits Stop bits Parity bits Error correction bits e actual data bytes are sent one a er another. then there is no way a computer could know that data was corrupt until it tried to work on it. In the case of both start and stop bits. but it is possible that you will have to work with the data parts. Parity simply takes a byte of data and counts the number of bits that have the value 1. you can ask for the data to be resent. of course. e situation stop bits try to address is familiar to anyone who uses a mobile phone. so when a 1 arrives it is easily recognised because there is something to detect. especially when you are using a serial system where data can be lost or subject to interference. Stop bits Stop bits are added to the end of data so that the receiver knows that the link is still active and didn’t unexpectedly drop out. If you are using even parity and one of the bits gets ipped. to give the circuitry at the far end a chance to wake up. stop and parity bits is piece of data is being transmitted with 1 start bit. however. is is called “even parity”. When data are being transmitted. If you are talking to someone and their message doesn’t get through to you properly. and keep asking until it comes through correctly. then there will be an odd number of 1s and you’ll know you have an error. and the most widely used is called parity. if there is an even number of 1s it adds a 0. how would you know that it had arrived? at’s where a start bit comes in.The software developer’s view of the hardware with is Universal Serial Bus (USB) protocol which has become a very popular way of connecting devices (almost replacing all the others).Start. What if. but with modern circuits this now uncommon. As programmers we need not concern ourselves with the electrical and mechanical parts of a protocol. there will always be an even number of them. but as computer data is meaningless 0s and 1s. the 0 is the rst bit in the data. If you get an error. or a 0 into a 1. if two bits got ipped. at means that if you count up the number of 1s in a byte with even parity. A start bit is a 1 that is added to the start of the transmission of data. erefore a system is needed so that the computer (or at least the communications electronics) can work out if something has gone wrong and ask for a correction. then the transmission is ended. until they have all been sent. It doesn’t matter if the data starts with a 1 or a 0 it is always added. Whether this is acceptable will depend on how reliable the data transmission HSC Course 271 . By complying with this protocol devices made by one manufacturer should work with devices made by another manufacturer. what you hear won’t make sense to you and you can ask them to repeat it. so hwo do you tell the di erence between a 0 and just nothing happening.

which is named a er its inventor Richard Hamming. is process is repeated until all of the data have been received successfully. longer sets of data can be encoded and checked. Some computers use memory that has in-built parity so that memory errors can be easily detected. 4) code where 7 bits are used to encode 4 bits of data (the other 3 are the error system bits) which means you have an increase in size of 75% in the data stream. CRC works by performing mathematical operations on each byte of a block of data. Programming of hardware devices Processing data streams Processing data when they arrive is no more di cult than packaging it up to be sent in the rst place. ere are many real-world systems where these limitations are critical to success and so other error systems must be used.The software developer’s view of the hardware system is. One of the code systems that avoids some of the problems of parity is the Hamming code system. the start and stop bits only occur at the beginning and end of the whole stream. Each piece will contain the number of bits the protocol speci es and the parity bit if one is used. a er its inventors. it has exactly the same advantages and disadvantages as even parity. Odd parity is less commonly used than even mainly for historical reasons.it all gets transmitted and received the same way. it’s ability to only detect a single error. cross out the parity bits. Clearly the CRC method of doing things is very e cient if the probability of an error is low. then less intensive methods of error detection can be used. e use of a Reed-Solomon (255. the two outermost planets in the solar system. ere are two main problems with parity. On a bad transmission medium it can be very ine cient because an error of just 1 bit in 1024 bytes can cause the entire block to be resent. When there is likely to be less of a problem with interference. a 27% increase. so that’s a 14% increase in data transmission. 15) code where 19 bits are used to send 15 bits of data. then parity is ne. How that data will be interpreted is. Clearly you have to have know the protocol that is being used so you can make sense of all the bits. but once you know whether start and stop bits are being used. it then checks its result with the CRC data sent by the sender. such as the (19. As the data arrive at the receiver. up to the program that uses it . they are not attached to each byte. Hamming codes are not the only ones used for error correction and detection. but you still want to allow for the fact that there might be errors. if the stream has multiple bytes in it. part of an mp3 le. and what sort of parity is being used (if any) then the process is fairly straight forward. When parity was rst used it was added to 7-bit ASCII code. Of course nothing is free. the data is considered alright. and that you can’t x that error except by having the data retransmitted. of course. and can easily be built into electronics. if they are correct.the same data could be text. If the two values are the same. if there is a di erence. checking and correcting Hamming codes are not complex. a request is made to resend the entire block of data. Other versions are a bit more e cient. What you are le with is the transmitted data. pixels in an image or pretty much anything else . it performs the same calculations on the arriving data. e simplest version is the (7. and one real world case shows how important these codes can be. In 1977 the United States launched Voyager I and II on journeys to Jupiter and Saturn to take colour photographs and record lots of other data. By cleverly adjusting the path Voyager II took around Saturn it was possible to send it on to both Uranus and Neptune. although they are beyond the scope of the SDD course. Begin by identifying the start and stop bits if they are being used. One of the more common systems is the Cyclic Redundancy Check or CRC.500 million km to Earth could be corrected and the images and other data successfully decoded. Odd parity also exists. and remove them from the data stream. HSC Course 273 . e exact mathematics involved in making. Remember. By the time Voyager II got to Neptune in 1989 signals from the spacecra took four and a half hours to reach Earth. so if there were any problems with the data there was no way for them to be retransmitted 272 as the cra only recorded about 15 minutes worth of information. By constructing the codes in di erent ways. so there was an extra 1 bit added for every 7 transmitted. If errors are rare and so the chances of two errors in the same byte is very small. 223) code meant that errors introduced by the signal travelling over 4. another system is known as Reed-Solomon codes. and the cost of using parity is that the amount of information you transmit is greater than if you didn’t worry about error detection. allows you to detect two errors and correct one error in any given data package. e next step is to divide the data up into byte sized pieces. usually 256 to 1024 bytes and then passing along the results of its check. in this case the total number of 1s in a byte plus the parity bit will be odd rather than even. One of the trade-o s in system design is the loss of speed in exchange for more reliable data transmission. Check each byte for correct parity if it is being used. e Hamming system.

or perhaps error detection information. including header information. but now there are programming environments that allow a developer to work in a high level language such as C or C++ and have the machine code loaded onto the controller. some memory and a little bit of input and output circuitry. or to select from a set of options that a device might have. For example if you are using a barcode scanner. that is has the correct start and stop bits and parity.The software developer’s view of the hardware Decoding data e following stream of data is received. either sensing or commanding. If you are working with a speci c device. header. ese are normally just settings that you include in your program when you set up the serial communications controller. Header information is o en required to set the device up. this leaves 000001100010110110001000 Because we know that the data are 7-bit integers with a parity bit. 1000011000101101100010001 e protocol uses one start bit. a good video message program will expect a reply from the receiver telling it how well the data are being received so that it can adjust the speed of data transmission if information is being delayed unacceptably or lost. e header information might modify the meaning of the transmitted data. One of the reasons that ovens and washing machines have become so much more complex is that they no longer have to rely on electrical and mechanical devices to control them. Once your program has collected all it needs. instead an embedded controller can do the work. When it comes to programming the rst thing is to make sure that the data you are sending will be in the correct format. 2 × 1. is o en happens when you are working on a system where specialised hardware has been developed for a speci c purpose. and the manufacturer would normally supply the interface code you’d need . 2 × 1 so all the data are valid. Controller chips will be connected to a sensor. is to remove the parity bits 0000011 0010110 1000100 Convert these back to decimal numbers 3. Header information may need to include information about the data that are to follow it. ere may be header data to check and remove. e header data would include information about where the cover information is within the le so that it can be turned into a picture rather than a sound. For example an mp3 le might contain an album cover picture in addition to the music. If a complex error detection system is being used then the received data may need to be checked as a block. For example. that is all that can be stored on the chip. and how the device expects those commands to be packaged. and that it will be sent at the right speed.the gate system might be built by another section of your company and simply uses a serial interface to connect to the controlling computer. and so that needs to be taken into account. however. Begin by removing the start and stop bits. To control the device you need to add any required header information. O en you will need to do this even if the device is primarily used for input. 274 . 68 e next step Processing the data might also obligate your program to respond in some way so that the transmitting program knows that the data were received correctly. 22. you might nd yourself needed to produce output which targets a speci c device. the data are three 7-bit integers. Controllers are simple single chip devices that contain a CPU. You want to work out if the data are correct and what the values are. one stop bit and even parity. set to it to tell it what barcode systems it should read or ignore. Originally these embedded controller chips were programmed directly in machine language. You’ll just get the command list and protocol instructions. yet clever programming can make them do quite complex operations. the manufacturer will normally supply a manual which speci es what commands are needed for what functions. or you’re working for a device manufacturer. or how long to wait a er a successful read to ensure that the same barcode isn’t read multiple times. data and trailing information it can then pass it to the hardware that will actually control the transmission of the data. rather than a generic one. For example you could be working on a system which reads the barcode on a ticket and then opens an entrance gate if the ticket is valid. ese sensors may be HSC Course 275 Generating output to an appropriate device If you nd yourself working with a device for which the manufacturer hasn’t provided drivers. normally break down into just two di erent types of operations. Controller chips typically have only limited capabilities. Whenever the controller starts up it will automatically begin running the installed so ware. While barcode readers are quite common. or an array of sensors which let them know about what is going on. ese do. and still. there might be a need to store anything received until all the parts of the transmission have been received. 00000110 00101101 10001000 Now check that the data are valid (that there is an even number of 1s in each byte). we divide this data into groups of 8. Programming of hardware devices Control systems Embedded controllers have become a common addition to many devices. It may be necessary for your program to collect all the data and store it so it can calculate the header information such as the number of bytes in the data. 4 × 1. Programs can be written that are then loaded onto memory on the controller. some units require data. Once the raw data gets to the program it will have to process it further.

usually by using a loop to read each value. it might be overloaded and so it doesn’t move the expected amount. you might need to write code for one of these printers. In particular it 1F Unit separator would be unusual for even a highly specialised piece of equipment to not use one of the standard methods of interfacing with a computer. e controller monitors the input signals. electromagnetic latches such as those on some security doors. Programming of hardware devices Code 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A Function Nothing Start of heading Start of text End of text End of transmission Enquiry Acknowledge Ring bell Backspace Tab Start new line Vertical tab Start new page Carriage return Shi in Shi out Data link escape Device speci c Device speci c Device speci c Device speci c Negative acknowledge Idle End of block Cancel End of paper Substitute Printer operation In the past. a thermometer that senses the temperature of an oven. change the colour of the ribbon being used for the printing. using the standard codes for printing Roman and other European language codes . 276 Specialist devices 1B Escape If you are working as a programmer in many industries you may have to program devices that are speci c to that industry and consequently 1C File separator aren’t supplied with all the programming tools that are available for 1D Group separator things like printers or hard disk drives.8 . the sequence 1B 70 30 19 FA will cause a cash drawer attached to the printer to pop open. Other codes can make the printer’s bell ring 07 or 09 will make the printer skip to the next tab stop. printers were noisy mechanical devices that printed one character at a time. not all of which would be used with a printer. which is any device which causes something to move. and what each will do is determined by the printer that is being used. e output might also be passed to an actuator. e programming integrates all the inputs to determine if something needs to be done. so a controller can instruct a stepper motor to move a certain amount and it will . HSC Course 277 . in those cases a digital to analog converter (DAC) is used to convert the digital value to an analog voltage. and so feedback is usually necessary. e reason is Table 19. can be di cult to control. When you apply some power to a motor for a particular length of time. Using an escape sequence such as this is a very common printer control technique.8 shows the all 32 control codes. Modern printers are considerably more sophisticated than their predecessors. is isn’t quite as bad as it seems 1E Record separator though because although the device might be unique the components with which it is built are likely to be fairly standard. and are now usually controlled by sending a le that describes how the page is to be printed. serial or parallel communications. e HSC. So were you to nd yourself writing point-ofsale so ware for low-end systems. or switch modes to print very simple graphics or characters from other languages. or an encoder that determines the position of a motor . the non-printing characters in ASCII.but even these are o en controlled by page description languages. For example on an Epson U220 receipt printer.The software developer’s view of the hardware buttons on the front of the washing machine. it won’t always turn the same amount.or pretty much anything else that can give out a digital value. Changing modes is controlled by sending control codes which are values from 0-31. O en a feedback system will be used where some of the inputs directly monitor the output devices and provide feedback on what is happening. expects you to know how to program printers that are largely no longer made. apart from printing characters. cut the paper. maybe a simple 7 segment LED or maybe a more complex screen. Control of these devices is simple. code 0A causes the paper to advance one line so that the printing will be on a new line. the controller can monitor what the motor is doing and adjust its output further if necessary. let you advance paper. none of these printers works with Unicode characters. for example the code 0D causes the print head to return to the le hand side to start printing again. Specialised motors called stepper motors can be used to simplify this process as they include an encoder and monitor themselves. On the output side a controller chip will be connected to display devices of some type. because the devices have fairly limited capabilities. Simple actuators are electric motors which turn while power is applied and stop otherwise. ere are a number of codes that are speci cally for device control. By putting an encoder on the motor which turns its motion into numbers. Most of the control codes are standard. the processor in the printer then translates that into instructions that the print engine uses to produce the page. or increasingly USB. e 1B rst character is the escape character and tells the printer that the codes following aren’t letter codes. O en these codes are followed by standard ASCII values to add information. It then determines whether or not any values need to be sent to the output devices and sends them if necessary. e last bastion of these type of printers are the small receipt printers that some shops use . Typically all these types of printers work with 8-bit ASCII codes. however. Table 19. and one line a er another. in particular.ASCII control codes. Typical options for this type of printer. but are part of the command. the load on the motor may have changed.as far as I have been able to tell. and certainly would not be seriously considered in any new system.the controller need not monitor the process. Sensors that don’t have a direct digital value will be connected to an analog to digital converter (ADC) which converts the measurement to a digital value. Combining the two makes the printer begin printing at the beginning of a new line. e programming in most controllers is fairly straight forward. Some devices can’t take a digital value to control them. Motors.

0001765 5. to a programmer it will just be a stream of data formatted according to a protocol designed as part of the device. -81 2. 11010101 4. 217. 00110111 d.3175 b.97214 c. if the answer is negative leave the result in 2s complement form. 01101100 b. or what format a command takes to have it send the data. so unless there is some very compelling reason. 6. use the 2s complement representation. integrated circuits which handle all the protocol and transfer are easily and cheaply available. 1.The software developer’s view of the hardware simple. 23 + 19 b. Perform the following subtractions using binary numbers. Convert the following 8-bit 2’s complement binary numbers to their decimal representations. ese numbers are in IEEE 754-2008 format. 0. 11010101 3. 278 HSC Course 279 . In each case make the binary number 8-bits long. of course. a. Increasingly other devices that don’t look like a conventional desktop or laptop computer have a computer style interface for programmers to use. a. 87 + 52 c. 231 b. Programming of hardware devices Exercises Worked solutions to these exercises can be found beginning on page 299. Devices such as mobile phones and games consoles provide programming environments which are similar to those seen on the more conventional machines. 54 + 17 d. it doesn’t matter whether the devices at the end are the massive electric motors that drive the axes of a 4 metre astronomical telescope or a 7 segment LED counting down time on a washing machine. detailing how it will present data at the interface. Most of our work is likely to be involved with the programming away from the interface. 01101100 b. e program you write will probably just have to use the available protocol to read data from the various sensors in the device and send data to the displays. Any special commands the device needs or that it may send and how to send it the data it needs to perform a task. a. b. a.with. a. 10101010 c. 00110111 d. Convert the following 8-bit positive binary integers to their decimal representations. 4 d. Convert these decimal integers to their binary representations. 10101010 c. -0. Convert the following 32-bit fractions to their decimal equivalents. Convert these numbers from their decimal to their binary representations. and actuators . and in the case of negative integers. along with some additional limitations. -74 c. Generally you will be supplied with a description of the protocol the data uses from the engineers who built it. a. e nice part is that the communications all turns out to be simple data transfer.0031789 d. 19 + 189 7. some processing in between. -6. the cheap and easy solution is the way to go. Perform the following additions using binary numbers.

53 87 .29 29 .The software developer’s view of the hardware a. c.94 Programming of hardware devices 280 HSC Course 281 .112 47 . d. b. 53 .

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.