C Programming for Game Developers, Module II 1st edition by e Institute Publishing, Inc. 1584504528‎ 978-1584504528pdf download
C Programming for Game Developers, Module II 1st edition by e Institute Publishing, Inc. 1584504528‎ 978-1584504528pdf download
https://ebookball.com/product/c-programming-for-game-developers-
module-ii-1st-edition-by-e-institute-publishing-
inc-1584504528aeurz-978-1584504528-25190/
https://ebookball.com/product/introduction-to-80-86-assembly-
language-and-computer-architecture-1st-edition-by-richard-c-
detmer-isbn-0763746622-9780763746629-9016/
https://ebookball.com/product/introduction-to-80-86-assembly-
language-and-computer-architecture-1st-edition-by-detmer-
isbn-0763717738-9780763717735-12404/
https://ebookball.com/product/charles-river-media-1st-edition-by-
game-programming-gems-ii-isbn-10118/
https://ebookball.com/product/mathematics-for-game-
developers-1st-edition-by-christopher-
tremblay-159200038x-9781592000388-23640/
Machine Learning for Cybersecurity Cookbook Over 80 recipes on how to
implement machine learning algorithms for building security systems
using Python 1st edition by Emmanuel Tsukerman 9781838556341
1838556346
https://ebookball.com/product/machine-learning-for-cybersecurity-
cookbook-over-80-recipes-on-how-to-implement-machine-learning-
algorithms-for-building-security-systems-using-python-1st-
edition-by-emmanuel-tsukerman-9781838556341-1/
https://ebookball.com/product/c-game-programming-cookbook-for-
unity-3d-2nd-edition-by-jeff-
murray-9781000359725-1000359727-18762/
https://ebookball.com/product/beginning-c-game-programming-1st-
edition-by-michael-dawson-isbn-1592002056-9781592002054-12450/
https://ebookball.com/product/professional-javascript-for-web-
developers-1st-edition-by-nicholas-c-zakas-
isbn-1118026691-9781118026694-16162/
https://ebookball.com/product/beginning-c-game-programming-1st-
edition-edition-by-michael-dawson-
isbn-1592002056-9781592002054-25056/
C++ Programming for
Game Developers
Module II
All brand names and product names mentioned in this book are trademarks or service marks of their
respective companies. Any omission or misuse of any kind of service marks or trademarks should not be
regarded as intent to infringe on the property of others. The publisher recognizes and respects all marks
used by companies, manufacturers, and developers as a means to distinguish their products.
E-INSTITUTE PUBLISHING titles are available for site license or bulk purchase by institutions, user
groups, corporations, etc. For additional information, please contact the Sales Department at
[email protected]
Table of Contents
MODULE II OVERVIEW........................................................................................................................................................1
CHAPTER 10: INTRODUCTION TO TEMPLATES ..........................................................................................................2
INTRODUCTION ........................................................................................................................................................................3
CHAPTER OBJECTIVES .............................................................................................................................................................3
10.1 CLASS TEMPLATES...........................................................................................................................................................4
10.1.1 Class Template Definition .......................................................................................................................................7
10.1.2 Class Template Implementation ..............................................................................................................................7
10.1.3 Class Template Instantiation...................................................................................................................................8
10.2 EXAMPLE: A TABLE TEMPLATE CLASS.............................................................................................................................9
10.2.1 Table Data...............................................................................................................................................................9
10.2.2 Class Interface.......................................................................................................................................................10
10.2.3 The destroy Method ..........................................................................................................................................11
10.2.4 The resize Method ............................................................................................................................................11
10.2.5 The Overloaded Parenthesis Operator .................................................................................................................13
10.2.6 The Table Class.....................................................................................................................................................13
10.3 FUNCTION TEMPLATES ..................................................................................................................................................17
10.3.1 Example Program .................................................................................................................................................18
10.4 SUMMARY ......................................................................................................................................................................21
10.5 EXERCISES .....................................................................................................................................................................21
10.5.1 Template Array Class............................................................................................................................................21
10.5.2 Template Bubble Sort Function.............................................................................................................................22
10.5.3 Table Driver ..........................................................................................................................................................22
CHAPTER 11: ERRORS AND EXCEPTION HANDLING...............................................................................................23
INTRODUCTION ......................................................................................................................................................................24
CHAPTER OBJECTIVES ...........................................................................................................................................................24
11.1 ERROR CODES ................................................................................................................................................................24
11.2 EXCEPTION HANDLING BASICS ......................................................................................................................................26
11.3 ASSERT ..........................................................................................................................................................................29
11.4 SUMMARY ......................................................................................................................................................................31
11.5 EXERCISES .....................................................................................................................................................................31
11.5.1 Exception Handling...............................................................................................................................................31
CHAPTER 12: NUMBER SYSTEMS ...................................................................................................................................33
INTRODUCTION ......................................................................................................................................................................34
CHAPTER OBJECTIVES ...........................................................................................................................................................34
12.1 NUMBER SYSTEMS .........................................................................................................................................................34
12.1.1 The Windows Calculator .......................................................................................................................................35
12.2 THE BINARY NUMBER SYSTEM ......................................................................................................................................37
12.2.1 Counting in Binary ................................................................................................................................................37
12.2.2 Binary and Powers of 2 .........................................................................................................................................38
12.2.3 Binary Arithmetic ..................................................................................................................................................39
Addition .......................................................................................................................................................................................... 39
Subtraction...................................................................................................................................................................................... 41
Multiplication ................................................................................................................................................................................. 43
12.2.4 Converting Binary to Decimal ..............................................................................................................................43
12.2.5 Converting Decimal to Binary ..............................................................................................................................44
12.3 THE HEXADECIMAL NUMBER SYSTEM...........................................................................................................................45
12.3.1 Counting in Hexadecimal......................................................................................................................................45
12.3.2 Hexadecimal Arithmetic ........................................................................................................................................46
Addition .......................................................................................................................................................................................... 46
i
Subtraction...................................................................................................................................................................................... 47
Multiplication ................................................................................................................................................................................. 48
12.3.3 Converting Hexadecimal to Binary .......................................................................................................................48
12.3.4 Converting Binary to Hexadecimal .......................................................................................................................49
12.4 BITS AND MEMORY ........................................................................................................................................................50
12.5 BIT OPERATIONS ............................................................................................................................................................51
12.5.1 AND.......................................................................................................................................................................51
12.5.2 Inclusive OR ..........................................................................................................................................................52
12.5.3 NOT.......................................................................................................................................................................52
12.5.4 Exclusive OR .........................................................................................................................................................53
12.5.5 Shifting ..................................................................................................................................................................53
12.5.6 Compound Bit Operators ......................................................................................................................................54
12.6 FLOATING-POINT NUMBERS ..........................................................................................................................................54
12.7 SUMMARY ......................................................................................................................................................................56
12.8 EXERCISES .....................................................................................................................................................................57
12.8.1 Binary Arithmetic ..................................................................................................................................................57
12.8.2 Hex Arithmetic.......................................................................................................................................................57
12.8.3 Base Conversions ..................................................................................................................................................58
12.8.4 Bit Operations .......................................................................................................................................................59
12.8.5 Binary to Decimal .................................................................................................................................................61
12.8.6 Decimal to Binary .................................................................................................................................................61
12.8.7 Bit Operation Calculator.......................................................................................................................................61
12.9 REFERENCES ..................................................................................................................................................................62
CHAPTER 13: STL PRIMER................................................................................................................................................63
INTRODUCTION ......................................................................................................................................................................64
CHAPTER OBJECTIVES ...........................................................................................................................................................64
13.1 PROBLEMS WITH ARRAYS ..............................................................................................................................................64
13.2 LINKED LISTS.................................................................................................................................................................66
13.2.1 Theory ...................................................................................................................................................................66
13.2.2 Traversing .............................................................................................................................................................71
13.2.3 Insertion ................................................................................................................................................................72
13.2.4 Deletion .................................................................................................................................................................73
13.3 STACKS ..........................................................................................................................................................................74
13.3.1 Theory ...................................................................................................................................................................74
13.3.2 Stack Operations ...................................................................................................................................................76
13.4 QUEUES .........................................................................................................................................................................78
13.4.1 Theory ...................................................................................................................................................................78
13.4.2 Queue Operations .................................................................................................................................................78
13.5 DEQUES .........................................................................................................................................................................80
13.5.1 Theory ...................................................................................................................................................................80
13.5.2 Deque Operations .................................................................................................................................................81
13.6 MAPS .............................................................................................................................................................................81
13.6.1 Theory ...................................................................................................................................................................81
13.6.2 Insertion ................................................................................................................................................................81
13.6.3 Deletion .................................................................................................................................................................82
13.6.4 Traversal ...............................................................................................................................................................82
13.6.5 Searching...............................................................................................................................................................83
13.7 SOME ALGORITHMS .......................................................................................................................................................84
13.7.1 Functors ................................................................................................................................................................84
13.7.2 Some More Algorithms..........................................................................................................................................88
13.7.3 Predicates..............................................................................................................................................................90
13.8 SUMMARY ......................................................................................................................................................................91
13.9 EXERCISES .....................................................................................................................................................................93
13.9.1 Linked List.............................................................................................................................................................93
13.9.2 Stack ......................................................................................................................................................................93
ii
13.9.3 Queue ....................................................................................................................................................................94
13.9.4 Algorithms .............................................................................................................................................................94
CHAPTER 14: INTRODUCTION TO WINDOWS PROGRAMMING ...........................................................................95
INTRODUCTION ......................................................................................................................................................................96
CHAPTER OBJECTIVES ...........................................................................................................................................................97
14.1 YOUR FIRST WINDOWS PROGRAM .................................................................................................................................97
14.2 THE EVENT DRIVEN PROGRAMMING MODEL ...............................................................................................................103
14.2.1 Theory .................................................................................................................................................................103
14.2.2 The MSG Structure...............................................................................................................................................103
14.3 OVERVIEW OF CREATING A WINDOWS APPLICATION ..................................................................................................104
14.3.1 Defining the Window Procedure .........................................................................................................................105
14.3.2 The WNDCLASS Structure...................................................................................................................................108
14.3.3 WNDCLASS Registration .....................................................................................................................................110
14.3.4 CreateWindow.....................................................................................................................................................110
14.3.5 Showing and Updating the Window ....................................................................................................................112
14.3.6 The Message Loop...............................................................................................................................................113
14.4 YOUR SECOND WINDOWS PROGRAM ...........................................................................................................................113
14.5 SUMMARY ....................................................................................................................................................................116
14.6 EXERCISES ...................................................................................................................................................................117
14.6.1 Exit Message .......................................................................................................................................................117
14.6.2 Horizontal and Vertical Scroll Bars....................................................................................................................117
14.6.3 Multiple Windows................................................................................................................................................117
14.6.4 Change the Cursor ..............................................................................................................................................117
14.6.5 Blue Background .................................................................................................................................................118
14.6.6 Custom Icon ........................................................................................................................................................119
CHAPTER 15: INTRODUCTION TO GDI AND MENUS...............................................................................................122
INTRODUCTION ....................................................................................................................................................................123
CHAPTER OBJECTIVES .........................................................................................................................................................123
15.1 TEXT OUTPUT ..............................................................................................................................................................124
15.1.1 The WM_PAINT Message....................................................................................................................................124
15.1.2 The Device Context .............................................................................................................................................124
15.1.3 TextOut ............................................................................................................................................................125
15.1.3 Example Program ...............................................................................................................................................126
15.2 SHAPE PRIMITIVES .......................................................................................................................................................131
15.2.1 Drawing Lines .....................................................................................................................................................131
15.2.2 Drawing Rectangles ............................................................................................................................................137
15.2.3 Drawing Ellipses .................................................................................................................................................141
15.3 LOADING AND DRAWING BITMAPS ..............................................................................................................................142
15.3.1 Loading ...............................................................................................................................................................142
15.3.2 Rendering ............................................................................................................................................................145
15.3.3 Deleting ...............................................................................................................................................................146
15.3.4 Sample Program..................................................................................................................................................146
15.4 PENS AND BRUSHES .....................................................................................................................................................150
15.4.1 Pens .....................................................................................................................................................................150
15.4.2 Brushes................................................................................................................................................................151
15.5 SHAPE CLASSES ...........................................................................................................................................................152
15.5.1 Class Definitions .................................................................................................................................................152
15.5.2 Class Implementations ........................................................................................................................................154
15.6 MENUS .........................................................................................................................................................................157
15.6.1 Creating a Menu Resource..................................................................................................................................157
15.6.2 Loading a Menu and Attaching it to a Window...................................................................................................160
15.6.3 Checking Menu Items ..........................................................................................................................................160
15.6.4 Selecting Menu Items ..........................................................................................................................................161
iii
15.7 THE PAINT SAMPLE......................................................................................................................................................161
15.8 SUMMARY ....................................................................................................................................................................171
15.9 EXERCISES ...................................................................................................................................................................172
15.9.1 Colors..................................................................................................................................................................172
15.9.2 Styles ...................................................................................................................................................................172
15.9.3 Cube ....................................................................................................................................................................172
15.9.4 Undo Feature ......................................................................................................................................................172
CHAPTER 16: INTRODUCTION TO DIALOGS AND CONTROLS............................................................................173
INTRODUCTION ....................................................................................................................................................................174
CHAPTER OBJECTIVES .........................................................................................................................................................174
16.1 MODAL DIALOG BOXES; THE STATIC TEXT CONTROL; THE BUTTON CONTROL .........................................................175
16.1.1 Designing the Dialog Box ...................................................................................................................................175
16.1.2 Modal Dialog Box Theory...................................................................................................................................179
16.1.3 The About Box Sample ........................................................................................................................................181
16.2 MODELESS DIALOG BOXES; THE EDIT CONTROL ........................................................................................................184
16.2.1 Modeless Dialog Box Theory ..............................................................................................................................184
16.2.2 The Edit Box Sample: Designing the Dialog Resource .......................................................................................186
16.2.3 The Edit Box Sample ...........................................................................................................................................187
16.3 RADIO BUTTONS ..........................................................................................................................................................191
16.3.1 Designing the Radio Dialog Resource ................................................................................................................191
16.3.2 Implementing the Radio Button Sample ..............................................................................................................192
16.4 COMBO BOXES .............................................................................................................................................................196
16.4.1 Designing the Combo Box Dialog Resource .......................................................................................................197
16.4.2 Implementing the Combo Box Sample.................................................................................................................197
16.5 SUMMARY ....................................................................................................................................................................201
16.6 EXERCISES ...................................................................................................................................................................202
16.6.1 List Box................................................................................................................................................................202
16.6.2 Checkbox Controls ..............................................................................................................................................202
16.6.3 File Save and Open Dialogs................................................................................................................................204
16.6.4 Color Dialog .......................................................................................................................................................206
CHAPTER 17: TIMING, ANIMATION, AND SPRITES.................................................................................................207
INTRODUCTION ....................................................................................................................................................................208
CHAPTER OBJECTIVES .........................................................................................................................................................208
17.1 TIMING AND FRAMES PER SECOND ..............................................................................................................................208
17.1.1 The Windows Multimedia Timer Functions.........................................................................................................208
17.1.2 Computing the Time Elapsed Per Frame ............................................................................................................211
17.1.3 Computing the Frames Per Second.....................................................................................................................213
17.2 DOUBLE BUFFERING ....................................................................................................................................................214
17.2.1 Motivation ...........................................................................................................................................................214
17.2.2 Theory .................................................................................................................................................................214
17.2.3 Implementation....................................................................................................................................................215
17.3 TANK ANIMATION SAMPLE ..........................................................................................................................................220
17.3.1 Creation...............................................................................................................................................................222
17.3.2 Destruction..........................................................................................................................................................222
17.3.3 Input ....................................................................................................................................................................223
17.3.4 Updating and Drawing........................................................................................................................................224
17.3.5 Point Rotation .....................................................................................................................................................228
17.3.6 Tank Application Code........................................................................................................................................229
17.4 SPRITES ........................................................................................................................................................................237
17.4.1 Theory .................................................................................................................................................................237
17.4.2 Implementation....................................................................................................................................................241
17.5 SHIP ANIMATION SAMPLE ............................................................................................................................................245
17.5.1 Art Resources ......................................................................................................................................................245
17.5.2 Program Code .....................................................................................................................................................246
iv
17.6 SUMMARY ....................................................................................................................................................................254
17.7 EXERCISES ...................................................................................................................................................................255
17.7.1 Colors..................................................................................................................................................................255
17.7.2 Draw Order.........................................................................................................................................................255
17.7.3 Masking ...............................................................................................................................................................255
17.7.4 Make Your Own Sprite ........................................................................................................................................256
17.7.5 Bouncing Ball......................................................................................................................................................256
17.7.6 Modify the Ship Program ....................................................................................................................................256
17.7.7 Pong ....................................................................................................................................................................256
17.7.8 More on Animation..............................................................................................................................................257
CHAPTER 18: THE AIR HOCKEY GAME......................................................................................................................259
INTRODUCTION ....................................................................................................................................................................260
CHAPTER OBJECTIVES .........................................................................................................................................................260
18.1 ANALYSIS ....................................................................................................................................................................261
18.1.1 Object Identification............................................................................................................................................262
18.1.2 Game Behavior and Corresponding Problems to Solve......................................................................................262
18.2 DESIGN ........................................................................................................................................................................264
18.2.1 Algorithms ...........................................................................................................................................................264
18.2.1.1 Mouse Velocity ............................................................................................................................................................... 264
18.2.1.2 Red Paddle Artificial Intelligence ................................................................................................................................... 265
18.2.1.3 Puck Paddle Collision ..................................................................................................................................................... 267
18.2.1.4 Puck Wall Collision ........................................................................................................................................................ 272
18.2.1.5 Paddle Wall Collision ..................................................................................................................................................... 273
18.2.1.6 Pausing/Unpausing.......................................................................................................................................................... 275
18.2.1.7 Detecting a Score ............................................................................................................................................................ 275
18.2.2 Software Design ..................................................................................................................................................276
18.3 IMPLEMENTATION ........................................................................................................................................................280
18.3.1 Circle ..............................................................................................................................................................280
18.3.2 Rect ...................................................................................................................................................................281
18.3.3 AirHockeyGame ..................................................................................................................................................282
18.3.4 Main Application Code .......................................................................................................................................288
18.4 COLLISION PHYSICS EXPLANATION (OPTIONAL) .........................................................................................................295
18.4.1 Linear Momentum ...............................................................................................................................................296
18.4.2 Newton’s Second Law of Motion.........................................................................................................................297
18.4.3 Impulse Defined...................................................................................................................................................297
18.4.4 Newton’s Third Law of Motion ...........................................................................................................................298
18.4.5 Kinetic Energy and Elastic Collisions.................................................................................................................300
18.4.6 Collision and Response .......................................................................................................................................304
18.5 CLOSING REMARKS ......................................................................................................................................................308
v
Module II Overview
Module II is the second course in the C++ Programming for Game Developers series. Recall that in
Module I we started off by studying fundamental programming concepts like variables, console input
and output, arrays, conditional statements, strings, loops, and file input and output. We then pursued
higher level programming methodologies such as classes, object oriented programming design, operator
overloading, inheritance, and polymorphism. By now you should feel competent with the fundamentals
and at least comfortable with the higher level subject matter.
Our aim in Module II is twofold. Our first objective is to finish our study of C++ by examining
templates, error handling, the standard template library, and bitwise operations. Templates can be
thought of as a class factory, which allows us to generate similar yet unique classes, based on a code
template; this allows us to avoid duplicating code that is only slightly different. Error handling is an
important topic because things rarely work out as planned, and we will need to be able to detect
hardware failures, illegal operations, invalid input, corrupted and missing files, and the like in our code.
The standard template library is a set of generic ready to use C++ code that simplifies many day-to-day
programming tasks. In the STL chapter you will learn about several useful STL data structures and
algorithms, and the ideas behind them. The chapter on bitwise operations provides a deeper
understanding of computer memory and how numbers are represented internally. You will also learn
how to work in several other numbering systems such as binary and hexadecimal, which are more
natural from a computer’s point of view.
The second key theme in Module II is Windows programming. Here we will learn how to make familiar
Windows applications with resizable windows, mouse input, graphics, menus, dialog boxes, and
controls. In addition, we will learn how to implement 2D flicker free animation with double buffering,
and how to render 2D sprite images (i.e., graphical representation of game objects such as the main
character, landscape, and enemies). Finally, we conclude Module II by walking the reader through the
design and analysis of a fully functional 2D Air Hockey game, complete with graphics, physics,
artificial intelligence, and input via the mouse. This final project culminates much of the course
material.
By the end of this course, you will be well prepared for a first course in 3D game programming, as well
as many other interesting computer related fields that require an understanding of computer
programming as a qualification.
1
Chapter 10
Introduction to Templates
2
Introduction
You should recall from our discussions in Chapter 4 that std::vector can be thought of as a
“resizable array” (Section 4.6). However, what is interesting about std::vector is that we can
specify the type of vector to create with the angle bracket syntax:
vector<int> intVec;
vector<float> floatVec;
vector<bool> boolVec;
vector<string> stringVec;
Thus we can create vectors of different types, just as we can create elementary arrays of different types.
But, also recall that a std::vector is not some magical entity—it is just a class with methods that
handle the internal dynamic memory array resizing. So the question is: how can we create a generic
class that can work with any type (or at least, some types), like std::vector can? The answer to this
question leads us to C++ templates and, more generally, generic programming.
Before continuing on, we would like to say that the subject of templates is vast, and we can only
introduce the basics in this chapter. For advanced/interested readers, we refer you to C++ Templates:
The Complete Guide by David Vandevoorde and Nicolai M. Josuttis. This book should prove to be an
excellent resource for you and is a highly recommended supplement to the material we will study in this
chapter.
Chapter Objectives
3
10.1 Class Templates
Consider this small data structure, which represents an interval [a, b]:
struct FloatInterval
{
FloatInterval();
FloatInterval(float start, float end);
float midpoint();
float a;
float b;
};
FloatInterval::FloatInterval()
{
a = 0.0f;
b = 0.0f;
}
float FloatInterval::midpoint()
{
// return the midpoint between a and b.
return (a + b) * 0.5;
}
Although very simple, it is not hard to imagine the need for other types of intervals. For example, we
may want to describe integer intervals, character intervals, 3D vector intervals, and color intervals (color
values between two colors). The most obvious solution would be just to define these additional interval
classes. Here are a few of them:
struct IntInterval
{
IntInterval();
IntInterval(int start, int end);
int midpoint();
int a;
int b;
};
IntInterval::IntInterval()
{
a = 0.0f;
b = 0.0f;
}
4
IntInterval::IntInterval(int start, int end)
{
a = start;
b = end;
}
int IntInterval::midpoint()
{
// return the midpoint between a and b.
return (a + b) * 0.5;
}
struct CharInterval
{
CharInterval();
CharInterval(char start, char end);
char midpoint();
char a;
char b;
};
CharInterval::CharInterval()
{
a = 0.0f;
b = 0.0f;
}
char FloatInterval::midpoint()
{
// return the midpoint between a and b.
return (a + b) * 0.5;
}
This approach results in a lot of additional code. Moreover, we may need to create new interval types
later on, and we would then have to define additional classes. It does not take long to realize that this
process can become cumbersome pretty quickly.
Let us instead analyze the interval class to see if we can make any observations that will help us simplify
our task. We note that the only difference between FloatInterval and IntInterval is that
everywhere we see a float in FloatInterval, we see an int in IntInterval—and similarly with
FloatInterval and CharInterval. That is, these classes are essentially the same—only the type
they work with is different.
This gives us an idea. We could create a generic Interval class using a variable-type like so:
5
Struct Interval
{
Interval();
Interval(variable-type start, variable-type end);
variable-type midpoint();
variable-type a;
variable-type b;
};
Interval::Interval()
{
a = 0.0f;
b = 0.0f;
}
Then, if we could specify a type-argument, we could generate new Interval classes that worked the
same way, but with different types. All we have to do is substitute the type-argument for the variable-
type. For example, if we specified type float as the type argument (assume argument types are
specified in angle brackets < >), then the following class would be generated:
Interval<float> ==
struct Interval
{
Interval();
Interval(float start, float end);
float midpoint();
float a;
float b;
};
Note: The previous two code boxes do not use actual C++ syntax (though it is similar); pseudo-code
was used to illustrate the idea of how template classes work.
This behavior is exactly what template classes allow us to do. Returning to std::vector, when we
specify the type in the angle brackets, we instruct the compiler to create a vector class based on the
specified type by substituting the type-argument (type in angle brackets) into the type-variables of the
template vector class.
6
10.1.1 Class Template Definition
Now that we know what we would use templates for and the basic idea behind how they work, let us
examine the actual C++ template syntax. Here is how we would define a template Interval class in
C++:
template <typename T>
struct Interval
{
Interval();
Interval(T start, T end);
T midpoint();
T a;
T b;
};
The first line, template <typename T> indicates that the class is a template class. The parameter
inside the angle brackets <typename T> denotes a variable-type name—in this case, we named the
variable-type, T. Later, when we want to instantiate an Interval of, say, ints, the compiler will
substitute int everywhere there is a T.
There is some special syntax required when implementing the methods of a template class. In particular,
we must prefix the method with the template <typename T> syntax, and refer to the class name as
ClassName<T>. The following shows how we would implement the methods of Interval:
Again, observe how we use T to refer to the type, which will eventually be substituted into the template.
Note: The template functionality of C++ is not easy for compiler writers to implement.
7
10.1.3 Class Template Instantiation
We have already instantiated template classes earlier in Module I of this course, without your even
realizing it. For example, the following code generates two classes:
vector<int> intVec;
vector<float> floatVec;
It generates a vector class, where type int is substituted into the typename parameter, and it
generates a second vector class, where type float is substituted into the typename parameter. The
compiler generates these classes at compile time—after all, we specify the type-argument at compile
time. Once the int-vector and float-vector classes are generated (remember, generating these
classes is merely a matter of substituting the typename variable-type with the specified argument-
type), we can create instances of them. That is what intVec and floatVec are—they are instances of
the matching vector class generated by the compiler.
Note: To further clarify, classes of a particular type are generated only once. That is, if you write:
vector<float> f1;
vector<float> f2;
A float version of vector is not generated twice—it only needs to be generated once to instantiate
any number of float-vector object instances.
With our template Interval class defined and implemented, we can instantiate objects of various types
the same way we do with std::vector:
Note: A class can contain more than one typename. For example, we can define a class like so:
The above substitutes float for T1, and int for T2.
8
10.2 Example: A Table Template Class
For additional template practice, we will create a template Table class. A Table is sort of like
std::vector, except that instead of representing a resizable array, it represents a resizable 2D array—
or matrix. This table class will be very useful, as there are many datasets in game development that are
represented by a table (a game board/grid and 2D image immediately come to mind). We will want
tables of many kinds of data types, so naturally we will make a template Table class.
As we start off the design of our Table class, let us first discuss how we shall represent our table. For
starters, our table size will not be fixed—it will have m rows and n columns. Since the number of rows
and columns is variable, we must use dynamic memory. In this case, we use a pointer to an array of
pointers to arrays.
This probably sounds confusing, and it is definitely a bit tricky at first, but it will be pretty intuitive once
you think about it. We first have a pointer to an array, which we allocate dynamically. This array
describes the rows of the table. Now each element in this array is also a pointer. These pointers, in turn,
each point to another dynamic array, which forms the columns of the table. Figure 10.1 illustrates.
Figure 10.1: A 5x7 table represented with a pointer to an array of pointers to arrays. That is, we first have a pointer
to a “row” array. Each element in this row array, in turn, points to a “column,” thereby forming a 2D table.
9
Essentially, to have a variable sized 1D array, we needed one pointer to an array. To have a variable
sized 2D array (variable in both rows and columns), we need a pointer to an array of pointers to arrays.
Furthermore, we will want to maintain the number of rows and columns our table has. This yields the
following data members:
int mNumRows;
int mNumCols;
T** mDataMatrix;
The double star notation ** means “pointer to a pointer.” This is how we can describe a pointer to an
array of pointers to arrays.
As far as methods go, we need to be able to resize a table, construct tables, get the number of rows and
columns a table has, provide access to entries in the table, and overload the assignment operator and
copy constructor to provide deep copies since our class contains pointer data. The following definition
provides these features via the interface:
int numRows()const;
int numCols()const;
private:
// Make private because this method should only be used
// internally by the class.
void destroy();
private:
int mNumRows;
int mNumCols;
T** mDataMatrix;
};
10
The next three subsections discuss three non-trivial methods of Table. The implementations for the rest
of the methods are shown in Section 10.2.6.
The first method we will examine is the destroy method. This method is responsible for destroying
the dynamic memory allocated by a Table object. What makes this method a bit tricky is the pointer to
an array of pointers to arrays, which stores our table data. The method is implemented as follows:
Be sure to read the comments slowly and deliberately. First, we traverse over each row and delete the
column array that exists in each element of the row array (See Figure 10.1). Once we have deleted the
column arrays, we delete the row array.
In this section, we examine the resize method, which is relatively more complicated than the other
methods of the Table class. This method is somewhat tricky because it handles the memory allocation
of the pointer to an array of pointers to arrays; the method is presented below:
11
template <typename T>
void Table<T>::resize(int m, int n, const T& value)
{
// Destroy the previous data.
destroy();
// Save dimensions.
mNumRows = m;
mNumCols = n;
Again, be sure to read the comments slowly and deliberately. The method takes three parameters: the
first two specify the dimensions of the table; that is m by n. The third parameter is a default value to
which we initialize all the elements of the table.
The very first thing the method does is call the destroy method, as discussed in Section 10.2.3. This
makes one thing immediately clear -- we lose the data in the table whenever we call resize. If you
want to maintain the data, you will need to copy it into a separate table for temporary storage, resize the
current table, and then copy the data in the temporary storage back into the newly resized table.
After the resize method, we simply save the new dimensions. The next line:
allocates an array of pointers (see the row in Figure 10.1). What we must do now is iterate over each of
these pointers and allocate the column array:
12
After we have done this, we iterate over each column in the i-th row, and initialize the table entry with
value:
On the whole, it is not too complex if you break the method down into parts, and use Figure 10.1 as a
guide.
The final method we wish to discuss is the overloaded parenthesis operator. Although the
implementation is straightforward, we draw attention to this method because we have not overloaded the
parenthesis operator before.
Because C++ does not have a double bracket operator [][], which we can overload, we cannot index into
a table as we would a 2D array. We instead overload the parenthesis operator to take two arguments,
and instruct the method to use these arguments to index into the internal 2D array, in order to return the
i-th table entry. This allows us to index into a table “almost” like the double bracket operator would:
For reference, we provide the entire Table definition and implementation together here. Note in
particular how the definition and implementation are in the same file—this is necessary for templates.
You will be asked to use this class in one of the exercises, so be sure to give it a thorough examination.
// Table.h
#ifndef TABLE_H
#define TABLE_H
13
public:
Table();
Table(int m, int n);
Table(int m, int n, const T& value);
Table(const Table<T>& rhs);
~Table();
int numRows()const;
int numCols()const;
private:
// Make private because this method should only be used
// internally by the class.
void destroy();
private:
int mNumRows;
int mNumCols;
T** mDataMatrix;
};
14
mNumRows = 0;
mNumCols = 0;
*this = rhs;
}
15
template <typename T>
void Table<T>::resize(int m, int n, const T& value)
{
// Destroy the previous data.
destroy();
// Save dimensions.
mNumRows = m;
mNumCols = n;
mNumRows = 0;
mNumCols = 0;
}
#endif // TABLE_H
16
10.3 Function Templates
Template functions extend the idea of template classes. Sometimes you will have a function which
performs an operation that can be performed on a variety of data types. For example, consider a search
function; naturally, we will want to search arrays of all kinds of data types. It would be cumbersome to
implement a search function for each type, especially since the implementation would essentially be the
same—only the types would be different. So a search function is a good candidate for a template
design.
Next we see two template function examples, one that performs a linear search and a second template
function that prints an array.
The only operator LinearSearch uses on the type T is the equals == operator. Thus, any type we use
with LinearSearch (i.e., substitute in for T) must have that operator defined (i.e., overloaded). All the
built-in types have the equals operator defined, so they pose no problem, and similarly with
17
std::string. But if we wish to use user-defined types (i.e., classes) we must overload the equals
operator if we want to be able to use LinearSearch with them.
Similarly, the only operator Print uses on T is the insertion operator. Thus, any type we use with
Print (i.e., substitute in for T) must have that operator defined (i.e., overloaded). All the built-in types
have the insertion operator defined, so they pose no problem, and similarly with std::string. But if
we wish to use user-defined types (i.e., classes) we must overload the insertion operator if we want to be
able to use Print with them.
What follows is a sample program illustrating our template functions. We set up two arrays, a
std::string array, and an int array. We then use the Print function to print both of these arrays,
and we allow the user to search these arrays via LinearSearch. The key idea here is that we are using
the same template function for different types—that is, these functions are generic and work on any
types that implement the stated conditions (overloads the less than operator/insertion operator).
18
int main()
{
string sArray[8] =
{
"delta",
"lambda",
"alpha",
"beta",
"pi",
"omega",
"epsilon",
"phi"
};
int numStrings = 8;
Print(sArray, numStrings);
if( index != -1 )
cout << str << " found at index " << index << endl;
else
cout << str << " not found." << endl;
cout << endl;
//=======================================
// Int search.
Print(iArray, numInts);
int integer = 0;
cout << "Enter an integer to search for: ";
cin >> integer;
if( index != -1 )
cout << integer << " found at index " << index<<endl;
else
cout << integer << " not found." << endl;
cout << endl;
19
//=======================================
// Search again?
7 3 32 2 55 34 6 13 29 22 11 9 1 5
Enter an integer to search for: 32
32 found at index 2
Quit? (y)/(n)n
delta lambda alpha beta pi omega epsilon phi
Enter a string to search for: beta
beta found at index 3
7 3 32 2 55 34 6 13 29 22 11 9 1 5
Enter an integer to search for: 22
22 found at index 9
Quit? (y)/(n)n
delta lambda alpha beta pi omega epsilon phi
Enter a string to search for: phi
phi found at index 7
7 3 32 2 55 34 6 13 29 22 11 9 1 5
Enter an integer to search for: 0
0 not found.
Quit? (y)/(n)y
Press any key to continue
20
10.4 Summary
Sometimes we would like to create several versions of a class, where the only difference is the data
types involved. Template classes enable us to do this. Specifically, we create a generic class built using
generic type-variables, where we can then substitute real concrete types into these type-variables to form
new classes. The compiler forms these new classes at compile time. Template classes reduce the
number of classes that the programmer must explicitly write, and therefore, they save time and reduce
program size/complexity.
1. Template functions are generic and can work on any data type that implements the operations
used inside the function body. In this way, we can write one generic function that works for
several types, instead of a unique function for each type. Template functions reduce the number
of functions that the programmer must explicitly write, and therefore, they save time and reduce
program size/complexity.
2. Use templates for classes and functions, which can be generalized to work with more than one
type. std::vector, Table and LinearSearch are examples of classes and functions which
can be generalized in this fashion. The following exercises illustrate a few more examples, and
Chapter 13, on the STL, demonstrates a very sophisticated generic programming design.
10.5 Exercises
Reconsider the exercise from Section 7.9.2, where you were instructed to implement a resizable
FloatArray class:
// FloatArray.h
#ifndef FLOAT_ARRAY_H
#define FLOAT_ARRAY_H
class FloatArray
{
public:
// Create a FloatArray with zero elements.
FloatArray();
21
// Free dynamic memory.
~FloatArray();
private:
float* mData; // Pointer to array of floats (dynamic memory).
int mSize; // The number of elements in the array.
};
#endif // FLOAT_ARRAY_H
The problem with this class is that it only works with the float type. However, we would naturally
want resizable arrays of any type of object. Generalize the class with templates so that it can be used
with any type. Test your program by creating a std::string Array, and an int Array, from the
generic template class. Call the template class Array.
Reconsider the exercise from Section 3.7.8, where you were instructed to implement a Bubble Sort
function like so:
The problem with this function is that it only works with the int type; however, we would naturally
want to sort arrays of any type of object. Generalize the function with templates so that it can be used
with any type that implements the operations (e.g., less than, greater than, etc.) needed to implement the
bubble sort algorithm. Test your program by sorting a std::string array, and an int array, with the
template BubbleSort function.
Rewrite the exercise from Section 2.7.5, but instead use the Table class as discussed in Section 10.2,
instead of 2D arrays.
22
Chapter 11
23
Introduction
Throughout most of the previous chapters, we have assumed that all of our code was designed and
implemented correctly and that the results could be anticipated. For example, we assumed that the user
entered the expected kind of input, such as a string when a string was expected or a number when a
number was expected. Additionally, we assumed that the arguments we passed into function parameters
were valid. But this may not always be true. For example, what happens if we pass in a negative integer
into a factorial function, which expects an integer greater than or equal to zero? Whenever we allocated
memory, we assumed that the memory allocation succeeded, but this is not always true, because
memory is finite and can run out. While we copied strings with strcpy, we assumed the destination
string receiving the copy had enough characters to store a copy, but what would happen if it did not?
It would be desirable if everything worked according to plan; however, in reality things tend to obey
Murphy’s Law (which paraphrased says “if anything can go wrong, it will”). In this chapter, we spend
some time getting familiar with several ways in which we can catch and handle errors. The overall goal
is to write code that is easy to debug, can (possibly) recover from errors, and exits gracefully with useful
error information if the program encounters a fatal error.
Chapter Objectives
• Understand the method of catching errors via function return codes, and an understanding of the
shortcomings of this method.
• Become familiar with the concepts of exception handling, its syntax, and its benefits.
• Learn how to write assumption verification code using asserts.
Let us take a moment to look at a real world example of an error return code system. In particular, we
will look at the system used by DirectX (a code library for adding graphics, sound, and input to your
applications). Consider the following DirectX function:
24
Do not worry about what this function does or the data types this function uses, which you are not
familiar with.
This function has a return type HRESULT, which is simply a numeric code that identifies the success of
the function or an error. For instance, D3DXCreateTextureFromFile can return one of the following
return codes, which are defined numerically (i.e., the symbolic name represents a number). Which one
it returns depends upon what happens inside the function.
• D3D_OK: This return code means that the function executed completely successfully.
• D3DERR_NOTAVAILABLE: This return code means that the hardware cannot create a texture; that
is, texture creation is an “unavailable” feature. This is a failure code.
• D3DERR_OUTOFVIDEOMEMORY: This return code means that there is not enough video memory
to put the texture in. This is a failure code.
• D3DERR_INVALIDCALL: This return code means that the arguments passed into the parameters
are invalid. For example, you may have passed in a null pointer when the function expects a
valid pointer. This is a failure code.
• D3DXERR_INVALIDDATA: This return code means the source data (that is, the texture file) is not
valid. This error could occur if the file is corrupt, or we specified a file that is not actually a
texture file. This is a failure code.
• E_OUTOFMEMORY: This return code means there was not enough available memory to perform
the operation. This is a failure code.
By examining the return codes from functions that return error codes, we can figure out if an error
occurred, what potentially caused the error, and then respond appropriately. For example, we can write
the following code:
HRESULT hr = D3DXCreateTextureFromFile([...]);
25
DisplayErrorMsg("D3DERR_INVALIDCALL");
ExitProgram();
}
else if( hr == D3DXERR_INVALIDDATA )
{
DisplayErrorMsg("D3DXERR_INVALIDDATA");
ExitProgram();
}
else if( hr == E_OUTOFMEMORY )
{
DisplayErrorMsg("E_OUTOFMEMORY");
ExitProgram();
}
}
Here we simply display the error code to the user and then exit the program. Note that
DisplayErrorMsg and ExitProgram are functions you would have to implement yourself. They are
not part of the standard library.
FunctionCallB();
// Handle possible error codes
FunctionCallC();
// Handle possible error codes
...
Such a style of mixing error-handling code in with non-error-handling code becomes so cumbersome
that it is seldom religiously followed throughout a program, and therefore, the program becomes unsafe.
C++ provides an alternative error-handling solution called exception handling.
Exception handling works like this: in a segment of code, if an error or something unexpected occurs,
the code throws an exception. An exception is represented with a class object, and as such, can do
anything a normal C++ class object can do. Once an exception has been thrown, the call stack unwinds
(a bit like returning from functions) until it finds a catch block that handles the exception. Let us look at
an example:
26
Program 11.1: Exception Handling.
#include <iostream>
#include <string>
using namespace std;
class DivideByZero
{
public:
DivideByZero(const string& s);
void errorMsg();
private:
string mErrorMsg;
};
DivideByZero::DivideByZero(const string& s)
{
mErrorMsg = s;
}
void DivideByZero::errorMsg()
{
cout << mErrorMsg << endl;
}
int main()
{
try
{
float quotient = Divide(12.0f, 0.0f);
cout << "12 / 0 = " << quotient << endl;
}
catch(DivideByZero& e)
{
e.errorMsg();
}
}
The very first thing we do is define an exception class called DivideByZero. Remember that an
exception class is just like an ordinary class, except that we use instances of it to represent exceptions.
27
The next item of importance is in the Divide function. This function tests for a “divide by zero” and if
it occurs, we then construct and throw a DivideByZero object exception. Finally, in the main
function, in order to catch an exception we must use a try-catch block. In particular, we wrap the code
that can potentially throw an exception in the try block, and we write the exception handling code in
the catch block. Note that the catch block takes an object. This object is the exception we are
looking to catch and handle.
It is definitely possible, and quite common, that a function or method will throw more than one kind of
exception. We can list catch statements so that we can handle the different kinds of exceptions:
try
{
SomeFunction();
}
catch(LogicError& logic)
{
// Handle logic error exception
}
catch(OutOfMemory& outOfMem)
{
// Handle out of memory exception
}
catch(InvalidData& invalid)
{
// Handle invalid data
}
In addition to a chain of catches, we can “catch any exception” by specifying an ellipses argument:
try{
SomeFunction();
}
catch(...){
// Generic error handling code
}
As a final note, be aware that this section merely touched on the basics of exception handling, and there
are many more details and special situations that can exist. Also note that the functionality of exception
handling is not free, and introduces some (typically minor) performance overhead.
28
11.3 Assert
In general, your functions and methods make certain assumptions. For example, a “print array” function
might assume that the program passes a valid array argument. However, it is possible that you might
have forgotten to initialize an array, and consequently, passed in a null pointer to the “print array”
function, thus causing an error. We could handle this problem with a traditional error handling system
as described in the previous two sections. However, such errors should not be occurring as the program
reaches completion. That is, if you are shipping a product that has a null pointer because you forgot to
initialize it then you should not be shipping the product to begin with. Error handling should be for
handling errors that are generally beyond the control of the program, such as missing or corrupt data
resources, incompatible hardware, unavailable memory, flawed input data, and so on.
Still, for debugging purposes, it is very convenient to have self-checks littered throughout the program
to ensure certain assumptions are true, such as the validity of a pointer. However, based on the previous
argument, we should not need these self-checks once we have agreed that the software is complete. In
other words, we want to remove these checks in the final version of the program. This is where assert
comes in.
To use the assert function you must include the standard library <cassert>. The assert function
takes a single boolean expression as an argument. If the expression is true then the assertion passes;
what was asserted is true. Conversely, if the expression evaluates to false then the assertion fails and a
dialog box like the one depicted in Figure 11.1 shows up, along with an assertion message in the console
window:
29
The information the assertion prints to the console is quite useful for debugging; it displays the condition
that failed, and it displays the source code file and line number of the condition that failed.
The key fact about asserts is that they are only used in the debug version of a program. When you
switch the compiler into “release mode” the assert functions are filtered out. This satisfies what we
previously sought when we said: “[…] we want to remove these checks [asserts] in the final version
of the program.”
To conclude, let us look at a complete, albeit simple, program that uses asserts.
PrintIntArray(array, 10);
}
Because we pass a null pointer into PrintIntArray, in main, the assert fails and the dialog box and
assert message as shown in Figure 11.1 appear. As an exercise, correct the problem and verify that the
assertion succeeds.
30
11.4 Summary
1. When using error codes to handle errors for every function or method we write, we have it return
a value, which signifies whether the function/method executed successfully or not. If it
succeeded then we return a code that signifies success. If it failed then we return a predefined
value that specifies where and why the function/method failed. One of the shortcomings of error
codes is that for a single function call, we end up writing much more error handling code,
thereby bloating the size of the program.
2. Exception handling works like this: in a segment of code, if an error or something unexpected
occurs, the code throws an exception. An exception is represented with a class object, and as
such, can do anything a normal C++ class object can do. Once an exception has been thrown,
the stack unwinds (a bit like returning from functions) until it finds a catch block that handles the
exception. One of the benefits of exception handling is that the error-handling code (i.e., the
catch block) is not intertwined with non-error-handling code; in other words, we move all error
handling code into a catch block. This is convenient from an organizational standpoint. Another
benefit of exception handling is that we need not handle a thrown exception immediately; rather
the stack will unwind until it finds a catch block that handles the exception. This is convenient
because, as functions can call other functions, which call other functions, and so on, we do not
want to have error handling code after every function/method. Instead, with exceptions we can
catch the exception at the top level function call, and any exception thrown in the inner function
calls will eventually percolate up to the top function call which can catch the error. Be aware
that the functionality of exception handling is not free, and introduces some performance
overhead.
3. To use the assert function, you must include the standard library <cassert>. The assert
function takes a single boolean expression as an argument. If the expression is true then the
assertion passes; what was asserted is true. Conversely, if the expression evaluates to false then
the assertion fails and a message is displayed along with a dialog box. The key fact about
asserts is that they are only used in the debug version of a program. When you switch the
compiler into “release mode” the assert functions are filtered out.
11.5 Exercises
This is an open-ended exercise. You are to come up with some situation in which an exception could be
thrown. You then are to create an exception class representing that type of exception. Finally, you are
to write a program, where such an exception is thrown, and you should catch and handle the exception.
It does not have to be fancy. The goal of this exercise is for you to simply go through the process of
creating an exception class, throwing an exception, and catching an exception, at least once.
31
Chapter 12
33
Introduction
For the most part, with the closing of the last chapter, we have concluded covering the core C++ topics.
As far as C++ is concerned, all we have left is a tour of some additional elements of the standard library,
and in particular, the STL (standard template library). But first, we will take a detour and become
familiar with data at a lower level; more specifically, instead of looking at chars, ints, floats, etc.,
we will look at the individual bits that make up these types.
Chapter Objectives
• Learn how to represent numbers with the binary and hexadecimal numbering systems, how to
perform basic arithmetic in these numbering systems, and how to convert between these
numbering systems as well as the base ten numbering system.
• Gain an understanding of how the computer describes intrinsic C++ types internally.
• Become familiar with the way in which floating-point numbers are represented internally.
Throughout this chapter, we will become familiar with two other specific number systems, particularly
the base two binary system and the base sixteen hexadecimal systems. We choose these systems
because they are convenient when working with computers, as will be made clear in Section 12.4.
These new numbering systems may be cumbersome to work with at first, but after a bit of practice you
will become very fast at manipulating numbers in these systems.
In order to distinguish between numbers in different systems, we will adopt a subscript notation when
the context might not be clear:
34
12.1.1 The Windows Calculator
Microsoft Windows ships with a calculator program that can work in binary, octal (a base eight number
system we will not discuss), decimal, and hexadecimal. In addition to the arithmetic operations, the
program allows you switch (i.e., convert) from one system to the other by simply selecting a radio
button. Furthermore, the calculator program can even do logical bit operations AND, OR, NOT, XOR
(exclusive or), which we discuss in Section 12.5. Figures 12.1a-12.1e give a basic overview of the
program.
Figure 12.1a: The calculator program in “standard” view. To use the other number systems we need to switch to
“scientific” view.
Figure 12.1b: The calculator program in “scientific” view. Notice the four radio buttons, which allow us to switch
numbering systems any time we want.
35
Figure 12.1c: Here we enter a number in the decimal system. We also point out the logical bit operations AND, OR,
NOT, and XOR (exclusive or), which are discussed in Section 12.5.
Figure 12.1d: Here we switched from decimal to binary. That is, “11100001” in binary is “225” in decimal. So we can
input a number in any base we want and then convert that number into another base by simply selecting the radio
button that corresponds to the base we want to convert to. In addition, we also point out that the program
automatically limits you to two possible values in binary.
36
Figure 12.1e: Here we switched from binary to hexadecimal. That is, “11100001” in binary is “E1” in hexadecimal,
which is “225” in decimal. We also point out that there are now sixteen possible hexadecimal numbers to work with.
Do not worry too much about this now; we discuss hexadecimal in Section 12.3.
You can use this calculator program to check your work for the exercises.
The binary number system is a base two number system. This means that only two possible values per
digit exist; namely 0 and 1. In binary, we count similarly to the way we count in base ten. For example,
in base ten we count 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and then, because we have run out of values, to count ten
we reset back to zero and add a new digit which we set to one, to form the number 10.
In binary, the concept is the same except that we only have two possible values per digit. Thus, we end
up having to “add” a new digit much sooner than we do in base ten. We count 0, 1, and then we already
need to add a new digit. Let us count a few numbers one-by-one in binary to get the idea. For each
number, we write the equivalent decimal number next to it.
37
0 2 = 010
12 = 110
There is no ‘2’ in binary—only 0 and 1—so at this point, we must add a new digit:
10 2 = 210
112 = 310
Again, we have run out of values in base two, so we must add another new digit to continue:
100 2 = 410
1012 = 510
110 2 = 610
1112 = 710
1000 2 = 810
10012 = 910
1010 2 = 1010
10112 = 1110
1100 2 = 1210
11012 = 1310
1110 2 = 1410
11112 = 1510
10000 2 = 1610
It takes time to become familiar with this system as it is easy to confuse the binary number 11112 for the
decimal number 111110 until your brain gets used to distinguishing between the two systems.
An important observation about the binary number system is that each “digit place” corresponds to a
power of 2 in decimal:
12 = 210
0
= 110
10 2 = 2110 = 210
100 2 = 210
2
= 410
1000 2 = 210
3
= 810
10000 2 = 210
4
= 1610
38
100000 2 = 210
5
= 3210
1000000 2 = 210
6
= 6410
10000000 2 = 210
7
= 12810
100000000 2 = 210
8
= 25610
1000000000 2 = 210
9
= 51210
10000000000 2 = 210
10 = 102410
100000000000 2 = 211
10 = 204810
1000000000000 2 = 212
10 = 409610
…
You should memorize these binary to decimal powers of two up to 212 10 = 409610 , in the same way you
memorized your multiplication tables when you were young. You should be able to recollect them
quickly. This will allow you to convert binary numbers into decimal numbers and decimal numbers into
binary numbers quickly in your head.
As an aside, in base ten we have a similar pattern, but because we are in base ten, the powers are powers
of ten instead of powers of two:
110 = 1010
0
1010 = 10110
10010 = 1010
2
100010 = 1010
3
1000010 = 1010
4
We can add numbers in binary just like we can in decimal. Again, the only difference being that binary
only has two possible values per digit. Let us work out a few examples.
Addition
Example 1:
10
+ 1
-----
?
39
We add columns just like we do in decimal. The first column yields 0 + 1 = 1, and the second also 1 + 0
= 1. Thus,
10
+ 1
-----
11
Example 2:
101
+ 11
------
?
Adding columns from right to left, we have 1 + 1 = 10 in binary for the first column. So we write zero
for this column and carry a one over to the next digit place:
1
101
+ 11
------
0
Adding the second column leads to the previous situation, namely, 1 + 1 = 10. So we write zero for this
column and carry a one over to the next digit place:
11
101
+ 11
------
00
Adding the third column again leads to the previous situation, namely, 1 + 1 = 10. So we write zero for
this column and carry a one over to the next digit place, yielding our final answer:
11
101
+ 11
------
1000
Example 3:
10110
+ 101
--------
?
Adding the first column (right most column) we have 0 + 1 = 1. So we write 1 for this column:
40
10110
+ 101
--------
1
10110
+ 101
--------
11
The third column yields 1 + 1 = 10, so we write zero for this column and carry over 1 to the next digit
place:
1
10110
+ 101
--------
011
1
10110
+ 101
--------
11011
Subtraction
Example 4:
10
- 1
-----
?
We subtract the columns from right to left as we do in decimal. In this first case we must “borrow” like
we do in decimal:
10
00
- 1
-----
?
41
10
00
- 1
-----
1
Example 5:
101
- 11
------
?
Subtracting the first column we have 1 – 1 = 0. So we write one in the first column:
101
- 11
------
0
Example 6:
10110
- 101
--------
?
In the second column we now have 0 – 0 = 0, in the third column we have 1 – 1 = 0, in the fourth
column we have 0 – 0 = 0, and in the fifth column we have 1 – 0 = 1, which gives the answer:
10
10100
- 101
--------
10001
42
Multiplication
Multiplying in binary is the same as in decimal; except all of our products have only four possible
forms: 0 × 0 , 0 × 1 , 1× 0 , and 1× 1 . As such, binary multiplication is pretty easy.
Example 7:
10
x 1
-----
10
Example 8:
101
x 11
------
101
+1010
------
1111
Example 9:
10110
x 101
--------
10110
000000
+1011000
---------
1101110
There is a mechanical formula, which can be used to convert from binary to decimal, and it is useful for
large numbers. However, in practice, we do not typically need to work with large numbers, and when
we do, we use a calculator. So rather than show you the mechanical way, we will develop a way to
convert mentally in our head. The mental conversion from binary to decimal relies on the fact that in the
binary number system, each “digit place” corresponds to a power of 2 in decimal, as we showed in
Section 12.2.2.
111000012
43
Other documents randomly have
different content
de façon à réaliser peu à peu l'enchaînement positif dont j'ai déjà
établi le principe.
Les mêmes motifs fondamentaux qui ont démontré, avec tant
d'évidence, au chapitre précédent, l'inévitable spontanéité générale
d'un état intellectuel pleinement théologique, n'auraient ici besoin
que d'être examinés avec plus de précision pour prouver, au moins
aussi clairement, que toujours et partout ce premier régime mental
de l'humanité a dû nécessairement commencer par un état complet,
plus ou moins prononcé mais ordinairement très durable, de pur
fétichisme, constamment caractérisé par l'essor libre et direct de
notre tendance primitive à concevoir tous les corps extérieurs
quelconques, naturels ou artificiels, comme animés d'une vie
essentiellement analogue à la nôtre, avec de simples différences
mutuelles d'intensité. Cette constitution originaire des spéculations
humaines serait sans doute difficile à méconnaître aujourd'hui, soit
qu'on l'examinât à priori du point de vue rationnel où nous place
l'ensemble de la théorie biologique de l'homme, soit en l'étudiant à
posteriori d'après tous les renseignemens exacts que l'on peut
combiner sur ce premier âge social: enfin, l'appréciation judicieuse
du développement individuel confirmerait évidemment, à cet égard,
l'analyse immédiate de l'évolution collective. Beaucoup de
philosophes sont néanmoins parvenus, d'après des méthodes vagues
et vicieuses, à obscurcir profondément des notions aussi
irrécusables, en s'efforçant d'établir, au contraire, que le point de
départ intellectuel a dû consister dans le polythéisme proprement
dit, c'est-à-dire dans la croyance spontanée à des êtres surnaturels,
distincts et indépendants de la matière, passivement soumise, pour
tous ses phénomènes, à leurs volontés suprêmes. Quelques-uns
même, qui, malgré leur prétendue résolution préalable de tout
examiner librement, subissaient, à leur insu, l'empire, si rarement
évitable, des opinions vulgairement consacrées, sont allés jusqu'à
intervertir entièrement la progression naturelle des idées
théologiques, en voulant représenter le monothéisme rigoureux
comme la véritable source primordiale, d'où seraient ensuite issus,
par corruption graduelle, le fétichisme après le polythéisme[2]. Il
serait certainement superflu de s'arrêter ici à discuter aucunement
ces diverses aberrations, si manifestement contraires, non-
seulement à l'ensemble des observations les plus décisives sur
l'homme et sur la société, mais encore à toutes les lois les mieux
établies sur la marche nécessairement toujours graduelle de notre
intelligence, jusque dans ses plus simples exercices. A tous égards,
notre vrai point de départ, intellectuel ou moral, est inévitablement
beaucoup plus humble que ne l'indiquent ces fantastiques
suppositions: l'homme a partout commencé par le fétichisme le plus
grossier, comme par l'anthropophagie la mieux caractérisée; malgré
l'horreur et le dégoût que nous éprouvons justement aujourd'hui au
seul souvenir d'une semblable origine, notre principal orgueil collectif
doit consister précisément, non à méconnaître vainement un tel
début, mais à nous glorifier de l'admirable évolution dans laquelle la
supériorité, graduellement développée, de notre organisation
spéciale, nous a enfin tant élevés au-dessus de cette misérable
situation primitive, où aurait sans doute indéfiniment végété toute
espèce moins heureusement douée.
Note 2: Une telle hypothèse ne saurait être vraiment
soutenable que pour ceux qui admettent, à cet égard, une
révélation directe et spéciale, suivant l'esprit du système
catholique. Encore faudrait-il, même alors, concevoir cette
révélation comme presque continue, ou du moins fréquemment
renouvelée, afin de combattre sans cesse le retour toujours
imminent à la marche vraiment naturelle: ainsi que le vérifie
clairement le cas des Hébreux, malgré leur divin enseignement,
fortifié des précautions les plus puissantes et les mieux
soutenues, incapables néanmoins, en tant d'occasions, d'y
contenir suffisamment l'instinct spontané vers l'idolâtrie primitive.
ebookball.com