0% found this document useful (0 votes)
69 views

EEET2246 - Engineering Computing 1: Course Revision Dr. Glenn Matthews Dr. Samuel Ippolito

EEET2246

Uploaded by

JIM LIN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

EEET2246 - Engineering Computing 1: Course Revision Dr. Glenn Matthews Dr. Samuel Ippolito

EEET2246

Uploaded by

JIM LIN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

EEET2246 – Engineering

Computing 1
Course Revision
Dr. Glenn Matthews
Dr. Samuel Ippolito
EEET2246 – Final Test Revision
• Congratulations on completing the core of EEET2246.
– The final assessment is the “Final Test” – 20%
– The laboratories accounted for 57% (Tasks – 26%, Tests - 31%) of the assessment,
whilst the tutorial quizzes contributed 23% (Quiz 1 – 8%, Quiz 2 – 15%).
– Laboratory marks will be finalised late next week, so check Canvas ‘Grades’ to
ensure all marks are consistent.

• The final test consists of both multiple choice, short- and long-answer
questions.
– An example of the test will be released on the Canvas subject webpage.
– For every multiple choice question there are up to five possible answers.
– Select the answer that is ‘most correct’.
– That is an answer which contains all relevant information, but no falsehoods.
– Multiple choice questions score a point for a correct answer and no points for an incorrect
answer. No answer scores zero.
– The marks will be stated for other question types.
– All answers are to be entered in Canvas.
– You may be required to use Visual Studio 2019 as part of the assessment.
– Ensure that your licence is current as no concessions will be given during the assessment.
– Only use Visual Studio if the questions states you should otherwise you will run out of time.

RMIT University © 2020 School of Engineering - E & B 2


EEET2246 – Final Test Revision
• The process of studying for tests varies from person to person.
– Read through the lecture notes and make notes as you go.
– Powerpoint Slides and sample code are all available on the Canvas subject website.
– Tutorial solutions have been released.
– The sample solution (worked problem) has also been released, however as a .pdf file.
– THESE SLIDES MAY NOT CONTAIN ALL EXAMINABLE MATERIAL
– The code examples in the lecture notes are very important.
– Attempt the “Projects” in the lecture notes / textbook.
– The quiz sections in the textbook can be used to confirm your knowledge.

• The laboratories are also essential.


– Examine the results from the “Autotester” and see where you may have lost marks.
– Attempt to fix the “bugs” in your code.
– Try to avoid just reading the report and “thinking” you understand it.
– The real knowledge is in doing!!

• Lectures are also available via Collaborate Ultra.

RMIT University © 2020 School of Engineering - E & B 3


EEET2246 - Practical Study Hints
• Review all your Laboratory Material
– Rewrite your Laboratory 1, 2 and 3 solutions so that it passes all the tests
successfully.
– Rewrite the different sections of Laboratories using different methods and
algorithms. Write different versions of your solutions and use:
– Arrays with index notation.
– Arrays with pointers.
– Functions for different aspects of your code:
– Pass data by value.
– Pass data by pointers (reference).
– Pass data by reference parameters.

• Review all 5 tutorials


– Rewrite the solutions using the same methods as above.
– Look at the last few pages of each tutorial and answer the questions.
– This will greatly help you prepare for the final test.

• Review the first seven chapters of the Textbook


– Answer the Progress check questions as you go through each chapter.
– Attempt the small projects in each chapter.
– Attempt to answer the Mastery check questions at the end of each chapter.

RMIT University © 2020 School of Engineering - E & B 4


C++ Numeric Data Types
• Mathematically, there are two basic categories that numbers fall into.
– Integers which are whole numbers, both positive and negative.
– Integers = {0,1,2,3,4,-2,-1}
– Real Numbers which include all positive and negative numbers with fractional parts written past
the decimal point.
– Real Numbers = {0,1,1.3,-2.65,1.0025}
– In the realm of computer science, real numbers are represented with a floating-point type.

Variable Type Number Type Size (Bytes)


byte Small Integer 1
unsigned byte Small Positive Integer 1
short Integer 2
unsigned short Positive Integer 2
int Larger Integer 4
unsigned int Larger Positive Integer 4
long Even Larger Integer 4
unsigned long Even Larger Positive Integer 4
float Floating-point 4
double Floating-point with more accuracy 8
long double Floating-point with even more accuracy 10

RMIT University © 2020 School of Engineering - E & B 5


A Second Simple Program - Operators
• C++ also includes operators to perform mathematical
operations on data.
– C++ takes care of which version of the operator to use based on the data type.
– It is up to the programmer to make sure that they are performing the mathematical
operator on the correct variable.
– The compiler will still allow you to perform mathematical operators on character
data types which would result in a logical programming error.

Operator Sign
Addition +
Subtraction -
Multiplication *
Division /

• Once we knew how to use operators and variables, we wrote a


simplistic program to calculate the area of a rectangle and displayed it
on the console window.

RMIT University © 2020 School of Engineering - E & B 6


Program Control – The “if” Statement
• The “if” statement evaluates the ‘condition’ based on the relational
operators.
– Using Object Oriented Programming (OOP) principals the programmer is not restricted to
comparing integer values.
– However, extreme care must be taken to make sure the condition performs a meaningful
comparison.
Operator Description
< Less than (eg. x < 10)
<= Less than or equal to (eg. x <= 10)
== Equivalence (eg. x == 10)
> Greater than (eg. x > 10)
>= Greater than or equal to (eg. x >= 10)
!= Not equivalent (eg. x != 10)

• A programming pitfall is trying to compare floating and double precision


numbers!
– The “if” statement compares to the precision of the value, thus it is often possible for two
‘identical’ floating point numbers to have different values after the decimal point. In this case
the comparison then fails.

RMIT University © 2020 School of Engineering - E & B 7


Control Statements – for Loops
• The basic “for” loop is used to repeat sections of code for a predefined
number of iterations.
– The data accessed within the loop can be regularly updated
within the loop.
– Example: Summation of all numbers within an array can be
calculated using a loop.
– A loop control variable can be either incrementing or
decrementing.

• The general form of the “for” loop is given by:

for ( init; condition; increment ) 
{
Code block statement(s);
}

Useful reference:
https://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm
RMIT University © 2020 School of Engineering - E & B 8
Data Storage in Modern Computing Systems
• Although we have a large range of data types, it is very important to understand
how they are stored and manipulated in common computing hardware.
– In a typical processor, data is stored in bytes.
– A byte consists of 8 bits.
– In a binary system a bit is the smallest unit.
– Binary consists of two discrete values – logic 0 (off) or logic 1 (on).
– Thus, 4 bytes = 4 * 8 bits = 32-bits.

• A storage location (memory) consists of two parts, the data and the address.
– The ‘specifier’ (variable name used by the programmer) is actually an alias for an address.
– The data is the actual value stored at that particular location.
– Consider the following example of memory storage in an Intel Processor.

Address: 0xFFFFFFFF 7 0

Address: 0xFFFFFFFE 7 0

Address: 0x00000001 7 0

Address: 0x00000000 7 0

RMIT University © 2020 School of Engineering - E & B 9


Character Escape Sequences
• Whilst most characters are easily printed on the screen or in a file, some such
as backspace, new line and carriage return are more difficult.
– Using control, or escape character sequences, we can create a symbolic equivalent that can be
used in standard input / output (I/O) streams.
– Typical examples we have used so far are “\n” (newline), “\t” (tab).
– The escape sequences also define other important characters such as a backslash “\\”
– Be wary with the backslash escape sequences as the compiler replaces every “\\” with a single “\”.

Escape Sequence Definition ASCII Character Number


\a Alert 7
\b Backspace 8
\r Carriage Return (<CR>) 13
\f Form Feed 12
\t Horizontal Tab 9
\n Newline 10
\v Vertical Tab 11
\” Double Quote 34
\’ Single Quote 39
\xN Hexadecimal Constant -
\\ Backslash -

RMIT University © 2020 School of Engineering - E & B 10


Relational and Logical Operators
• The logical operators are slightly more complex however can be used
to check for compound (multiple) conditions.
– C++ does not restrict how many compound conditions can be checked in one
statement.
– Logical operators are widely used in microprocessors and form the basis of the
assembler mnemonics (instruction set).
– Logical operators can be grouped using parenthesis similar to relational operators.
– Remember that relational and logical operators have a lower precedence than
arithmetic operators.
– The use of parenthesis is greatly encouraged!
– In order of precedence (highest first): ! (NOT), > (Greater Than), >= (GT or Equal To), < (Less Than),
<= (LT or Equal to), == (Equivalence), != (NOT Equal To), && (Logical AND), || (Logical OR)

Operator Description
! Logical NOT. For example, (!x) will evaluate to true of x is zero. This
simply toggles the Boolean value
&& Logical AND. For example, (x > 4 && y <= 10) will evaluate to true if
x is greater than four and y less than or equal to ten.
|| Logical OR. For example, (x > 10 || y < 10) will evaluate to true if
either x is greater than ten or y is less than ten.

RMIT University © 2020 School of Engineering - E & B 11


Control Statements – do-while loop
• The “do‐while” loop is a modified version of the “while” loop.
– In a “do‐while” loop the conditional expression is at the bottom of the loop.
– The body of the “do‐while” loop is executed at least once.
– Similar to the “while” loop the body of the loop is executed until the conditional
expression is true (non-zero).
– The general form of a “do‐while” loop is given by:

do 
{
Code block statement(s);
} while ( condition ); 

• So far three different iterative methods have been discussed, but


when would a programmer use a “for”, “while” and “do‐while”
loop?
– “for” loop – When the program needs to iterate a fixed number of iterations.
– “while” loop – When the program needs to iterate an unknown number of
iterations.
– “do‐while” loop – When the program needs to iterate at least once (condition is
checked after the first iteration).

RMIT University © 2020 School of Engineering - E & B 12


Introducing Arrays, Strings and Pointers
• C++ provides a wide variety of ‘tools’ to efficiently control program
execution and data storage.
– In this lecture we considered arrays, strings and pointers.
– Understanding one of these concepts aids in the understanding of the others.
– Many of these objects build on existing data types to improve access, provide
coherent storage and allow direct manipulation of memory addresses and the
corresponding contents.

• An array is a collection of variables of the same type that can be


accessed via an index.
– An array can be thought of as a list, a set of pigeon holes, or a table.

• A pointer is a variable that contains the memory address of a variable.


– Pointers often hold the start address of arrays.

• Based on these two concepts, a string can be thought of as an array


of characters.
– Strings can be of variable length and may contain escape characters such as
newline (\n) and horizontal tab (\t).
RMIT University © 2020 School of Engineering - E & B 13
Single-Dimension Arrays
• A single-dimension array is a list of related variables of the same
data-type.
– Examples may include bank account numbers, active users on a network or a list of
prices on a shopping docket.
– To generate a single-dimension array the programmer would use the construct:
data‐type name[size];
– The data-type is the base type of all the elements in the array (char, int, double).
– The size specifies how many variables of the base type make up the array.
– The name is what the array is called in the program.
– Given the array declaration:
int sample[10];
– “sample[10]” is an array of 10 integers in one continuous block of memory, each
integer consisting of 32 bits, or 4 bytes.

• To access an individual element of the array we need both the array


name and the corresponding index.
– For example, if the programmer wanted to assign the value of 15 to the first element
in the sample array they could write:
sample[0] = 15;
RMIT University © 2020 School of Engineering - E & B 14
Two-Dimensional Arrays
• C++ allows for multi-dimensional arrays to be created.
– Multi-dimensional arrays can be considered as a list of arrays.
– A two-dimensional array is the simplest multi-dimensional array and is declared via:
int twoD[5][7];
– The first index, 5, can be considered to be the number of rows, whilst the second index, 7, is the
number of available columns.
– In this case a total of 35 integers can be stored in the array.

Index 0 1 2 3 4 5 6
0 1 2 3 4 5 5 1
1 5 6 7 8 4 6 3
2 9 10 11 12 9 7 0
3 2 1 44 6 7 9 77
4 1 4 2 3 6 8 9

• To access array elements the programmer needs to use two indices and the
array name.
– To access a value at row 3, column 5 in array twoD the following notation could be used
(assuming tableValue has been defined):
tableValue = twoD[3][5]; // Access row 3, column 5.

RMIT University © 2020 School of Engineering - E & B 15


C++ Strings
• In C++ there are two main types of strings.
– “Null-Terminated” and C++ string type.

• The most common are single-dimension arrays of characters, called


“strings”, or “null-terminated strings” to be precise.
– As the name implies a “null-terminated string” is an array of characters ending with
a null (zero, ‘\0’) to indicate the end of the “string”.

• “Null-terminated strings” are widely used because they are very


efficient and allow very detailed control over “string” operations.
– Using an array of characters, which use a single byte, is similar to the methods a
computer uses to access memory.

• Generally when a programmer refers to a “string” it is a “null-


terminated string”.
– The null-terminator is represented as a ‘\0’ when written as a character.

RMIT University © 2020 School of Engineering - E & B 16


What are Pointers?
• A pointer is simply a variable that holds a memory address.
– Typically the address the pointer stores is that of another variable.

Type: Pointer Variable


Data Stored: Address Value

– If we create a pointer variable called ‘ip’ and ‘ip’ contained the memory address of a variable ‘y’,
then it is said that: “ip points to y”.
– Pointer variables are declared using the following syntax:
data‐type * var‐name;
– data-type determines what type of data the pointer will be “pointing to”.
– var-name is the C++ identifier used to name the pointer.

• So, how would the programmer define a pointer in their code?


– To create a pointer variable of base-type integer, the programmer would use the following
syntax:
int * myIntegerPointer; // Pointer to an integer type
– Furthermore, to define a pointer that contains the memory location of a floating-point data type
the following syntax can be used:
float * myFloatingPointer; // Pointer to a floating‐point data type.

RMIT University © 2020 School of Engineering - E & B 17


The Pointer Operators - &
• Similar to the standard C++ data-types mentioned in earlier lectures,
pointers have their own unique operators.
– C++ also allows other operations such as addition and subtraction on pointer types,
which was also discussed.

• The ampersand operator, &, is used to put the memory address of a


standard data-type (character, integer, floating-point) into the pointer
variable.
int total = 32000; // Create integer variable total.
int * ptr; // Create integer pointer variable ptr.
ptr = &total; // The memory address of the integer variable
// total is written to the pointer.

– Another method to interpret the ampersand operator is remember that & can be
thought as “returns the address of…”
– The & operator is a unary operator.
– That is, it takes only one argument, which in this case is the variable the programmer wants
to know the address of.

RMIT University © 2020 School of Engineering - E & B 18


The Pointer Operators - *
• The second operator is the asterisk operator, * , which is the
complement of the ampersand operator, &.
– The asterisk operator returns the value of the variable located at the address of the
pointer.
int total = 32000;
int value = 0;
int * ptr; // Declare an integer pointer variable
ptr = &total; // The memory address of the integer variable total 
// is written to the pointer.
value = *ptr; // Obtain the value stored at the address referenced by the pointer.

Variable Data Type Address (in bytes) Value


Program Execution

total Integer 0x2024 32000


value Integer 0x2028 0
ptr Integer Pointer 0x1024 ?

ptr Integer Pointer 0x1024 0x2024

value Integer 0x2028 32000

– Another method to interpret the * operator is remember that * can be thought as “the contents
at address…”
– Similar to the & operator, the * in also an unary operator.

RMIT University © 2020 School of Engineering - E & B 19


Assigning values through a pointer
• A pointer can be thought of as kind of pipe, or an indirect method of assigning
a value to a variable.
– Pointers can be used on the left hand side to assign values to the location pointed
to by the pointer.
int number = 0;     // Create an integer and assign 0.
int * p;        // Create an integer pointer.
p = &number;   // Assign the address of iNumber to the integer pointer.
*p = 101;        // Assigns the value 101 to the location pointed to by the integer       
// pointer p.

– Put another way, this example assigns the value 101 to the variable whose address
is p.
– When using pointers it is often advantageous to draw a memory map of the
program statements.
Program Execution

Variable Data Type Address (in Value


bytes)
number Integer 0x100 0
p Integer Pointer 0x200 ?
p Integer Pointer 0x200 0x100

number Integer 0x100 101

RMIT University © 2020 School of Engineering - E & B 20


Pointers and Arrays
• Pointers are arrays are closely related. Pointers and arrays are
interchangeable.
char str[80]; // Create a character array, 80 bytes long.
char * p1; // Create a character pointer called p1.
p1 = str; // Assign the address of array str to p1
– After the assignment p1 will point to str[0].

• When using an array without an index C++ automatically generates a pointer


to the first element, i.e. str[0].
– Be very careful when using an unindexed array in an expression as the compiler will generate a
pointer to the first element.

• Using either pointer arithmetic or the array index, identical elements in array
“str” can be accessed.
– If the programmer needs to access the 5th element in the array “str” either method can be used:
str[4] = 'r';
*(p1 + 4) = 'r';
– Parenthesis are required when using the pointer as the * operator would first find
the value pointed to by p1 and then add 4 to it.

RMIT University © 2020 School of Engineering - E & B 21


Using Arguments
• The information passed to a function is called the functions’ arguments
and are typically the way to pass actual values to a function.
– The values are then contained in variables.
– As an example, below is a function called box() that calculates the volume of a box.
void box(int length, int width, int height)
{
cout << "Volume of the box is: " << length * width * height << endl;
}
– Three arguments are passed to three parameters (integer variables).
Return Value: Function: Argument 1: Argument 2: Argument 3:
None (void) box length width height

– Parameters are variable declarations separated by commas.


– To call the function box(), the programmer must specify the function name as well as
three integer arguments.
box(7,20,4); // call box() function with arguments 7, 20, and 4
box(50,3,2); // call box() function with arguments 50, 3, and 2
box(8,6,9); // call box() function with arguments 8, 6, and 9

– Each of the arguments are copied to their matching parameter in the function
variable list. This is also known as “passing by value”.

RMIT University © 2020 School of Engineering - E & B 22


Passing a Pointer to an Array
There are three techniques to declare function parameters to receive
an array pointer:
• The first is to declare an array of the same size and type
– The declaration num[10] causes the
void display(int num[10])
compiler to automatically convert it to {
an integer pointer to the first element for(int i = 0; i < 10; i++)
of the array. cout << num[i] << " ";
– That is a pointer to the first element. cout << endl;
}
– When calling the function display(t),
i.e. the array name without an index,
the compiler converts this to a integer int main()
pointer and passes the address to the {
int t[10] = {1,2,3,4,5,6,7,8,9,10};
function.
display(t); // no need for the *
– The function display() then receives
return 0;
the address to the first element of the
}
array and uses it to display the
contents.
RMIT University © 2020 School of Engineering - E & B 23
Passing a Pointer
• In the first example the address of variable i was passed to the
function f(). A more elegant method is to directly pass the memory
address of i using the ampersand operator (as shown in Example 2).
– It is very important to understand that when a pointer is passed to a function the
function will be operating on the variable to which the pointer points.
– This allows the function to change the value of the variable without actually passing
the variable.
– The variable that is modified is not declared in the function and is outside the scope
of the function.
Program Execution

Variable Data Type Address (in bytes) Value Program Statement


i Integer 0x2024 32000 int i = 32000;
- - - - f(&i);
j Integer Pointer 0x1024 0x2024 void f(int * j)

i Integer 0x2024 100 *j=100;

RMIT University © 2020 School of Engineering - E & B 24


Returning a Value from a Function
• So far we have shown we can pass data to a function via an argument or
global variable.
– We can even get data back from a function if we use a global variable or a return.

• return types can be used by a programmer to return a value from a


function.
– To pass values back from the function, the programmer can use the return statement.
– The return statement makes the function return to the caller (prior routine)
immediately.
– All other statements beyond the return are simply ignored.
– For functions that do not return a value (i.e. void) the return statement is simply
return;
– If a return statement is not included in a void function, then the function will
naturally exit at the closing curly brace }.
– Functions can contain many return statements, however too many return statements
can make a function very confusing and ‘destructure’ it.
– Preferred method is a single return point.
– If using multiple return statements to exit early due to errors then a message should
be written to the console.

RMIT University © 2020 School of Engineering - E & B 25


Local Scope
• Local scope is created by a code block.
– Local variables declared within a block are only valid for that block.
– The variables cease to exist after the block in which they were declared finishes
executing.
for(int i = 0; i < 10; i++) if (x > y)
{ {
cout << "index = " << i << endl; int i = 0;
// do something // do something
} }

– After this code segment has finished the variable i is no longer available.
– C++ places the variable i in the “stack” when the code block executes, but deletes
it once execution has finished.
– The “stack” is a portion of computer memory used to store temporary data including return
addresses of functions and variables.
– In standard ‘C’ all variables should be defined at the start of the function.

• Variables are commonly declared in a function block.


– Such variables are private to the code and data within the given function block and
cannot be accessed by any statement outside the function.
– The only exception is when a variable is declared as a global variable (or its been
passed via a pointer).
RMIT University © 2020 School of Engineering - E & B 26
Variable Lifetime
• In summary, local variables declared within a block were only valid for
that block.
– Variables cease to exist after the block in which they were declared has finished
executing.
– If a value is given to the local variables in a function then that value will be erased
when the function finishes executing.
– If a block, such as a function block, is called repeatedly then all the variables within
that function are created and destroyed every time that function is called.

• This means that if a programmer wishes to permanently assign a


value to a variable that also exists outside a function a different
approach must be used.
– The first option is to pass the value by reference – The memory address of the
external variable.
– The second option is to return the new value of the variable. Whilst this is suitable
for single values, what happens when the programmer wants to return multiple
variables?
– The third option uses global variables.

RMIT University © 2020 School of Engineering - E & B 27


Global Scope
• Local variables are only known within the function in which they are
declared.
– How can a programmer create a variable that can be shared by many functions?
– The answer is to use global scope – The scope within which all other scope lives.
Declarative regions diagram

func2() local scope


global scope
int counter=0;
for loop local
scope

func1() local scope

next level up
local scope main()

– The local scopes live within the ‘sea’ of the global scope.
– Only a higher level scope can reach down into the lower levels and access all
variables below it.
– main(), func1() and func2() and all members within can access variables declared in
the global scope.

RMIT University © 2020 School of Engineering - E & B 28


Enumerations
• The keyword “enum” defines a list of integer constants.
– Each constant has a programmer defined name.
enum transport {car, truck, airplane, train, boat};
– By using the “enum” keyword the programmer has created a new variable type
called “transport”.
transport road = car;
transport sea = boat;
– transport is now a new data-type similar to an int , but it can only take the
values in the comma-separated list.

• The generic format for defining a list of enumerated constants is:


enum type_name {value‐list} variable‐list;
– It is possible to declare the new variables at the same time as defining the
enum type_name in one expression:
enum transport {car, truck, airplane, train, boat} vehicle;

User defined 0 1 2 3 4 Variable name
type name
RMIT University © 2020 School of Engineering - E & B 29
Binary to Decimal Conversion
2 3= 8 2 2= 4 2 1= 2 2 0= 1 Decimal
Use the Base 2 system
0 0 0 0 0
2n Decimal
0 0 0 1 1
20 1
0 0 1 0 2
21 2
0 0 1 1 3
22 4
0 1 0 0 4
23 8
0 1 0 1 5
24 16
0 1 1 0 6
25 32
0 1 1 1 7
26 64
1 0 0 0 8
27 128
1 0 0 1 9
28 256
1 0 1 0 10
29 512
1 0 1 1 11
210 1024
1 1 0 0 12
211 2048
1 1 0 1 13
212 4096
1 1 1 0 14
1 1 1 1 15

RMIT University © 2020 School of Engineering - E & B 30


Binary to HEX Conversion
2 3= 8 2 2= 4 2 1= 2 2 0= 1 HEX
0 0 0 0 0 41848 in decimal
0 0 0 1 1
16-bit register
0 0 1 0 2
0 0 1 1 3
0 1 0 0 4 Binary 1010 0011 0111 1000
0 1 0 1 5 Hex A 3 7 8
0 1 1 0 6
0 1 1 1 7
1 0 0 0 8 50644 in decimal
1 0 0 1 9
1 0 1 0 A
1 0 1 1 B
Binary 1100 0101 1101 0100
1 1 0 0 C
Hex C 5 D 4
1 1 0 1 D
1 1 1 0 E
1 1 1 1 F

RMIT University © 2020 School of Engineering - E & B 31


Bitwise AND
• The bitwise AND can be thought of as a convenient way to choose which bits to
turn off.
– The truth table and logic symbol for an AND operation is as follows:

a (input) b (input) c (output)


0 0 0
0 1 0 c = a & b
1 0 0
1 1 1

• Given the unsigned decimal numbers 211 and 170, what would be the result of:
int c = 211 & 170;
Binary Representation Decimal
1 1 0 1 0 0 1 1 211
1 0 1 0 1 0 1 0 170
1 0 0 0 0 0 1 0 130

– Be very careful, the statement c = 211 && 170 will assign 1 to c

RMIT University © 2020 School of Engineering - E & B 32


Bitwise OR
• The bitwise OR can be thought of as a convenient way to turn certain bits on.
– The truth table and logic symbol for an OR operation is as follows:

a (input) b (input) c (output)


0 0 0
0 1 1 c = a | b
1 0 1
1 1 1

• Given the unsigned decimal numbers 211 and 170, what would be the result of:
int c = 211 | 170;
Binary Representation Decimal
1 1 0 1 0 0 1 1 211
1 0 1 0 1 0 1 0 170
1 1 1 1 1 0 1 1 251

– Be very careful, the statement c = 211 || 170 will assign 1 to c

RMIT University © 2020 School of Engineering - E & B 33


Bitwise XOR
• The bitwise XOR (exclusive OR) sets a bit to logic 1 only if the bits compared
are different.
– The truth table and logic symbol for an XOR operation is as follows:

a (input) b (input) c (output)


0 0 0
0 1 1 c = a ^ b 
1 0 1
1 1 0

• Given the unsigned decimal numbers 211 and 170, what would be the result of:
int c = 211 ^ 170;
Binary Representation Decimal
1 1 0 1 0 0 1 1 211
1 0 1 0 1 0 1 0 170
0 1 1 1 1 0 0 1 121

• Be very careful, the statement c = 3^2 is not 32 (power of operation)


– For that you need to use: c = pow(3, 2);
RMIT University © 2020 School of Engineering - E & B 34
One’s Complement – NOT Operator
• The bitwise NOT simply inverts all the bits of an operand.
– The truth table and logic symbol for a NOT operation is as follows:

a (input) c (output)
0 1 c = ~a
1 0

• Given the unsigned decimal numbers 211, what would be the result of:
int c = ~211;
Binary Representation Decimal
1 1 0 1 0 0 1 1 211
0 0 1 0 1 1 0 0 44

void main() void main()


{ {
int var = 128;  // 0x80 unsigned int var = 128;  // 0x80
var = ~var; var = ~var;
cout << var << endl; cout << var << endl;
}   }  
Answer = -129 Answer = 4294967167

RMIT University © 2020 School of Engineering - E & B 35


The Shift Operators
• The shift operators “<<” and “>>” move all bits left or right the number of
places specified. int val = 120;   // 0x78 or 0111 1000
– To use the right shift operator the programmer would write: val = val >> 3;  // divide by 8
cout << val << endl; // val = 15
variable >> num_bits; // right shift (divide)
– The value of “num_bits” determines how many places each bit is shifted to the right.
– Each shift moves all bits right one position and brings in a zero to the left.

Start Bit Pattern Decimal


1 0 0 0 0 0 0 0 128
>> 1 0 1 0 0 0 0 0 0 64
>> 1 0 0 1 0 0 0 0 0 32
>> 1 0 0 0 1 0 0 0 0 16
>> 1 0 0 0 0 1 0 0 0 8
>> 1 0 0 0 0 0 1 0 0 4
>> 1 0 0 0 0 0 0 1 0 2
>> 1 0 0 0 0 0 0 0 1 1
>> 1 0 0 0 0 0 0 0 0 0

RMIT University © 2020 School of Engineering - E & B 36


Bitwise operations
• Clear bit 2 in a variable
var = 0x0F;   // existing value of variable
var = var & 0xFB; 

• Set a bits 0 and 1 without changing existing values


var = 0x80;  // existing value of variable
var = var | 0x03; 

• Toggle bits 7, 6 and 5 in a variable


var = 0xA0;  // existing value of variable
var = var ^ 0xE0; 

• Multiply a variable by 2
var = 0x40;     // existing value of variable
var = var << 1;

RMIT University © 2020 School of Engineering - E & B 37


Bitwise operations
• Divide a variable by 2
var = 0x40;     // existing value of variable
var = var >> 1;

• Divide a variable by 8
var = 0x40;     // existing value of variable
var = var >> 3;

• Invert bits in a variable


var = 0xE7;  // existing value of variable
var = var ^ 0xFF; 

• Clear bit 6 in a variable


var = 0x7F;    // existing value of variable
var = var & ~(1<<6);

RMIT University © 2020 School of Engineering - E & B 38


Bitwise operations
• Use of bitwise operation in conditional statement to check if bit 7 is
set:
var = 0xA8;
if ((var & 1<<7) == 1<<7)  // check 7th bit
cout << "Bit is set!" << endl;  
else 
cout << "Bit is not set!" << endl; 

• Use of bitwise operation in conditional statement to check if bit 3 and


bit 7 are set:

var = 0x8F;                            OR var = 0x8F;


if ( (var & 0x88) == 0x88 ) if ( (var & 1<<3) && (var & 1<<7) )
cout << "Bits are set!" << endl;   cout << "Bits are set!" << endl;  
else   else
cout << "Bits are not set!" << endl;  cout << "Bits are not set!" << endl; 

RMIT University © 2020 School of Engineering - E & B 39

You might also like