0% found this document useful (0 votes)
3 views47 pages

Lecture 1 PythonToCppPart1

Uploaded by

leen.nasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views47 pages

Lecture 1 PythonToCppPart1

Uploaded by

leen.nasser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Data Structures and Algorithms

Learning C++ from Python

Rasha Alkhansa

Electrical and Computer Engineering Department

Slides prepared by Prof. F. Zaraket and modified for Summer 2025


C++: aims in this course

Write small C++ programs to solve engineering problems


Read and understand large C++ programs
Learn differences with other languages by yourself
Know where and how to find what you need from C++ libraries
Ready for more advanced programming courses
Not in this course
A C++ expert programmer or a C++ language expert

2 / 38
Why C++

One of the most widely used languages in engineering areas


http://www.stroustrup.com/applications.html

C++ is precisely and comprehensively defined by an ISO standard


The most recent standard in ISO C++ 2023
C++ is available on almost all kinds of computers and operating
systems
C is the prominent system programming language
Low level programming interfaces in addition to a long history of
compilers with legacy optimizations make C/C++ practically more
efficient

3 / 38
C++ vs. Python: Compiled vs. interpreted

C/C++ is compiled while Python is interpreted


The compiled C++ program runs standalone
An interpreter runs the Python program within its context
No syntax surprises with C++ once code is compiled

4 / 38
C++ vs. Python: Compiled vs. interpreted

C/C++ is compiled while Python is interpreted


The compiled C++ program runs standalone
An interpreter runs the Python program within its context
No syntax surprises with C++ once code is compiled
C/C++ code is fed to a compiler
Preprocessing resolves libraries, headers and configurations
Compiler makes sure syntax is correct and translates code to assembly
language
Linker makes sure all code dependencies are resolved and links code to
libraries
A binary program compatible with the target machine is produced

4 / 38
C++ vs. Python: Compiled vs. interpreted—2

A binary program reduces runtime overhead consumed by the


interpreter
A binary program is a standalone distributable to customers
Original source code and IP rights are not exposed
Compilation guarantees syntax-error free code
Logical errors may still exist

5 / 38
C++ vs. Python: Compiled vs. interpreted—2

A binary program reduces runtime overhead consumed by the


interpreter
A binary program is a standalone distributable to customers
Original source code and IP rights are not exposed
Compilation guarantees syntax-error free code
Logical errors may still exist
On the other hand
A binary program is computer architecture (platform) dependent
We need to compile the program for each target architecture
Interpreted programs with solid interpreter support work across
machines
Interpreters support dynamic language features more easily
This also could be a nightmare

5 / 38
C++ vs. Python: Static and dynamic typing

C/C++ typing is more static


You need to specify variable types in C/C++
A variable is associated with a memory block
with a start address and a specific size associated with its type
C/C++ new standards introduced limited type inference support
C/C++ type inference also happens at compile time

6 / 38
C++ vs. Python: Static and dynamic typing

C/C++ typing is more static


You need to specify variable types in C/C++
A variable is associated with a memory block
with a start address and a specific size associated with its type
C/C++ new standards introduced limited type inference support
C/C++ type inference also happens at compile time
Python dynamic types are inferred
Names of variables are associated with objects
Operations are evaluated at run time for compatibility with objects
Reduces syntax dependency and improves algorithmic learning curve

6 / 38
C++ vs. Python: Static and dynamic typing

C/C++ typing is more static


You need to specify variable types in C/C++
A variable is associated with a memory block
with a start address and a specific size associated with its type
C/C++ new standards introduced limited type inference support
C/C++ type inference also happens at compile time
Python dynamic types are inferred
Names of variables are associated with objects
Operations are evaluated at run time for compatibility with objects
Reduces syntax dependency and improves algorithmic learning curve
Type declarations allow better memory management
Type declarations allow earlier detection of syntax, precision and
logical errors

6 / 38
Hello world program
#i n c l u d e < iostream >
i n t main ()
{
std :: cout << " Hello ! This is my first program . " << std :: endl ;
r e t u r n 0;
}

7 / 38
Hello world program
#i n c l u d e < iostream >
i n t main ()
{
std :: cout << " Hello ! This is my first program . " << std :: endl ;
r e t u r n 0;
}

iostream: input/output stream header file


#include: preprocessing directive, literally includes code from iostream
main: entry point execution function of the program
std: a namespace introduced by iostream
cout: console output stream, allows printing on console output
endl: delimiter designating a new line
braces: { code-block } contain code blocks
int: data type keyword, here specifies type of return value of main
return: completes function execution, and may return a value to caller

7 / 38
Hello world program — comments
// This is a line - comment preceded by comment - delimiters
#i n c l u d e < iostream > // similar ( not the same ) to import / Python
u s i n g namespace std ; // simplifies referring to objects in std
i n t main ()
{ // braces delimit code - blocks : no need for indentation
// indentation ( while not mandatory as in Python ) keeps code readable

// cout : console output object from iostream in namespace std


// operator << directs string and end - line to output
cout << " Hello world ! This is my first C ++ program . " << endl ;

/* This is a block comment surrounded by block - comment delimiters


main has an int ( integer ) return value
if it succeeds , it typically returns 0 to the system
if it fails , it typically returns a negative number
*/
r e t u r n 0;
}

Notice how we referred to cout and endl without std


Notice how statements end with semicolon ’;’

8 / 38
Comments

Comments are at least half of any programming language


Yet they are ignored by the compiler
Programmers/coders are authors. Who do we write code for?

Comments document your ideas and link your solution to code


Solve the problem in a language you think with
Document that thinking process with comments
Then translate (simplify) to a programming language
that is limited to what machines, compilers and interpreters can
understand

9 / 38
Comments

Comments are at least half of any programming language


Yet they are ignored by the compiler
Programmers/coders are authors. Who do we write code for?
The audience (readers)
Other programmers
Ourselves reading the code again
How much do you read code versus how much do you write when you
develop a program
Comments document your ideas and link your solution to code
Solve the problem in a language you think with
Document that thinking process with comments
Then translate (simplify) to a programming language
that is limited to what machines, compilers and interpreters can
understand

9 / 38
Building the program

We need to use an editor to type the program


Linux: vim, emacs, nano, and gedit
Windows: Microsoft visual studio integrated design environment (IDE)
MacOs: vim, emacs, and XCode (IDE)
QT creator (IDE) is available on all
Then we need to use a compiler to build the program
g++ on Linux/MacOs: g++ -o hello hello.cpp
The IDEs come with the integrated compilers
If program compiles with no errors, we run the program
./hello

10 / 38
C++ basic types

bool: a Boolean variable with a {true, false} domain


char: denotes a byte (8 bits) in memory
May represent 256 different characters
ASCII standard maps char to character representations
{−128, −127, . . . , 0, 1, . . . , 47, ‘0‘, ‘1‘, . . . , ‘9‘, 58, . . . ,
64, ‘A‘, ‘B‘, . . . , ‘Z ‘, 91, . . . , 96, ‘a‘, ‘b‘, . . . , ‘z‘, 122, . . . , 127}
int: 4-bytes integral number
Ranges over {−231 , . . . , −1, 0, 1, . . . , 231 − 1}
8-byte use is growing in new machines
double: floating point representation
4-bytes (on most compilers) for mantissa and 4-bytes for exponent
string: not built-in
Library supported type that handles character sequences
requires #include <string>

11 / 38
Declarations
#i n c l u d e < string >
Syntax
u s i n g namespace std ; typename variablename;
i n t main () { typename variablename=initialvalue;
bool b;
c h a r c = ’h ’;
typename variablename(initialvalue);
i n t y; variablename is a string
i n t x =0;
i n t a (4) ; Starts with a character in
double d; X = {_, a, b, . . . , z, A, B, . . . , Z }
d o u b l e z =0.2; Followed by any character in X ∪ {0, 1, . . . , 9}
string s ;
string name ( " eece330 " ) ;
r e t u r n 0; }
Examples above:
First line: bool is the type, variable name is ‘b’, and we did not provide
an initial value.
Fourth line: int is the type, variable name is ‘x’, and it is initialized to 4.

12 / 38
Declarations
#i n c l u d e < string >
Syntax
u s i n g namespace std ; typename variablename;
i n t main () { typename variablename=initialvalue;
bool b;
c h a r c = ’h ’;
typename variablename(initialvalue);
i n t y; variablename is a string
i n t x =0;
i n t a (4) ; Starts with a character in
double d; X = {_, a, b, . . . , z, A, B, . . . , Z }
d o u b l e z =0.2; Followed by any character in X ∪ {0, 1, . . . , 9}
string s ;
string name ( " eece330 " ) ;
r e t u r n 0; }

Semantics: a declaration allocates static memory


With enough storage space to represent the data type
Each variable is associated with an address in memory
(& variablename) operation returns the address
sizeof(variablename) returns the number of bytes

13 / 38
Assignment
Syntax
#i n c l u d e < string >
u s i n g namespace std ; variablename = expression;
i n t main () { variablename must be a declared variable
// construction
string crs ( " eece330 " ) ; expression must be an expression that
// assignment
crs = " eece 331 " ; evaluates to a value of a type compatible with
i n t x; variablename
x = 1024;
r e t u r n 0; } Multi-assignment on one line is not allowed
Semantics:
Store value of expression in memory corresponding to variablename
Python assignments infer (and may change) the type associated with
variablename based on expression
C++ incompatible assignments fire error messages
int x = 20; x = "hello"; error: invalid conversion from ‘const
char*‘ to ‘int‘

14 / 38
Assignments and type casting

C++ assignments and expressions support type casting


Loss of precision
AKA type demotion/promotion
double d = 2.2; int x = d; Truncates fraction part of d
User defined types may explicitly support type casting
Using constructors (Discussed later)
Using operator= overloading (Discussed later)
string s = "me"; s=13.4; s=99; works but may not be your
expected result (try it)

15 / 38
Arithmetic expressions

+, −, ∗, /, % are familiar
Shortcuts with assignment: + =, − =, ∗ =, / =
No ∗∗ exponentiation
C++ supports increment (++) and decrement (−−)
x++; is equivalent x=x+1;
y = x++; equivalent to y = x; x = x+1;
y = ++x; equivalent to x = x+1; y = x;
Decrement is similar

16 / 38
Relational operations

==, ! =, <, >, <=, >= are familiar


&& means and, || means or and ! stands for not
Expression 3 < x < 6 works but unlike math and Python produces
unexpected result

17 / 38
Relational operations

==, ! =, <, >, <=, >= are familiar


&& means and, || means or and ! stands for not
Expression 3 < x < 6 works but unlike math and Python produces
unexpected result
Say x is 1, Expression 3 < x evaluates “false” which is substituted for
by 0 in the expression
then 0 < 6 evaluates to “true”!
To get the correct answer use: (3 < x )&&(x < 6)

17 / 38
Conditional statements
Differences with Python
Parenthesis are required around expression
No colon (:)
Indentation is strongly recommended but not required
Indentation is not enough to specify a block of code
Must use open and close braces {} for conditional blocks of code of two or
more statements
In Python indentation is enough to specify a code-suite
No elif: use else if

i f ( ( x <= 5) && ( y > 0) ) {


u = 1;
cout << " block 1 " ;
} e l s e i f ( z != 3) {  
u = 2; > ./ a
cout << " block 2 " ; block 1
} else {  
u = 3;
cout << " block 3 " ;
}
18 / 38
Repetition: while loop
Parenthesis required for expression
Braces delimit code block

i n t i = 0; // initialize i
w h i l e ( i < 4) { // up to four trials
cout << " Guess x (0 <x <65) : " ;
cin >> x ; // read value
i f ( x == secret ) {  
cout << " you win ! " ; > ./ guess
i = 10; // force loop exit
Guess x (0 <x <65) : 32
} e l s e i f ( x < secret ) {
secret is smaller . Guess x (0 <x <65) : 16
cout << " secret is larger . " ;
secret is smaller . Guess x (0 <x <65) : 8
} else {
secret is smaller . Guess x (0 <x <65) : 4
cout << " secret is smaller . " ;
secret is smaller . you lose
}  
i = i +1; // Increment i
}
i f ( i == 4) {
cout << " you lose " ;
}

19 / 38
Repetition: while loop – break statement
Statement break; breaks the innermost loop
transfers execution to line directly after loop
when x is equal to secret break exits the loop

i n t i = 0; // initialize i
w h i l e ( i < 4) { // up to four trials
cout << " Guess x (0 <x <65) : " ;
cin >> x ; // read value
i f ( x == secret ) {
cout << " you win ! " ;  
b r e a k ; // Exit the loop . > ./ guess
} Guess x (0 <x <65) : 32
i f ( x < secret ) { // no need for else
secret is smaller . Guess x (0 < x <65) : 16
cout << " secret is larger . " ;
i = i +1;
secret is smaller . Guess x (0 < x <65) : 8
c o n t i n u e ; // iterate again secret is smaller . Guess x (0 < x <65) : 4
secret is smaller . you lose
} // no need for else
cout << " secret is smaller . " ;
 
i = i +1; // Increment i
}
i f ( i == 4) {
cout << " you lose " ;
}

20 / 38
Repetition: break with nested loops
w h i l e ( cond1 ) {
some code
w h i l e ( cond2 ) {
some code
b r e a k ; // Line A : go to Line X directly
some code
}
some code // Line X : Break from Line A leads to here
}
some code

21 / 38
Repetition: while loop – continue statement
Statement continue; continues iterating the loop
transfers execution to loop condition and ignores rest of current iteration
when x is less than secret continue ignores rest of current iteration
i n t i = 0; // initialize i
w h i l e ( i < 4) { // up to four trials
cout << " Guess x (0 <x <65) : " ;
cin >> x ; // read value
i f ( x == secret ) {
cout << " you win ! " ;  
b r e a k ; // Exit the loop . > ./ guess
} Guess x (0 <x <65) : 32
i f ( x < secret ) { // no need for else
secret is smaller . Guess x (0 < x <65) : 16
cout << " secret is larger . " ;
i = i +1;
secret is smaller . Guess x (0 < x <65) : 8
c o n t i n u e ; // iterate again secret is smaller . Guess x (0 < x <65) : 4
secret is smaller . you lose
} // no need for else
cout << " secret is smaller . " ;
 
i = i +1; // Increment i
}
i f ( i == 4) {
cout << " you lose " ;
}

22 / 38
Repetition: for loop
The for statement has four components
Initialization statement
Control (or condition) statetement
Increment (or update) statement
Code block (delimited by braces)
Syntax
for ( init; condition; increment) { code-block }
Semantics equivalent to
init; while(condition) { code-block increment; }

i n t sum = 0;
i n t sum = 0; i = 0;
f o r ( i = 0; i < n ; i = i +1) { w h i l e (i < n) {
cin >> x ; cin >> x ;
sum = sum + x ; sum = sum + x ;
} i = i +1;
}

23 / 38
Repetition: do/while loop variant
Sometimes you would like to perform at least one iteration
Syntax
do { code-block } while (condition);
Semantics equivalent to
code-block; while(condition) { code-block }

i n t number , sum = 0;
do {
cout << " Kindly enter a number : " ;
cin >> number ;
sum = sum + number ;
} w h i l e ( number != 0) ;
cout << " Sum is : " << sum ;

24 / 38
Control and repetition one line code blocks
If you forget to provide the open and close braces with
if, else, while, for, and do-while
Only the first next line is considered to be the code-block
Indentation has no meaning or effect (other than neat readability)
Missing braces is a serious source of confusion and mistakes
Becomes worse with nested loops and conditions
Can avoid mistakes by always using open and close braces to delimit code blocks
Note: a semi-colon is counted as a statement (an empty statement)
Common mistake: inserting a semi-colon directly after the if-condition
What would be the outcome of the first code block below if we add a
semi-colon after (a==0)?
i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
}

25 / 38
Control and repetition one line code blocks
If you forget to provide the open and close braces with
if, else, while, for, and do-while
Only the first next line is considered to be the code-block
Indentation has no meaning or effect (other than neat readability)
Missing braces is a serious source of confusion and mistakes
Becomes worse with nested loops and conditions
Can avoid mistakes by always using open and close braces to delimit code blocks
Note: a semi-colon is counted as a statement (an empty statement)
Common mistake: inserting a semi-colon directly after the if-condition
What would be the outcome of the first code block below if we add a
semi-colon after (a==0)?
i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
}

i f ( a == 0)
b = 10;
c = 10; // mistake if this
// was intended inside if 25 / 38
Control and repetition one line code blocks
If you forget to provide the open and close braces with
if, else, while, for, and do-while
Only the first next line is considered to be the code-block
Indentation has no meaning or effect (other than neat readability)
Missing braces is a serious source of confusion and mistakes
Becomes worse with nested loops and conditions
Can avoid mistakes by always using open and close braces to delimit code blocks
Note: a semi-colon is counted as a statement (an empty statement)
Common mistake: inserting a semi-colon directly after the if-condition
What would be the outcome of the first code block below if we add a
semi-colon after (a==0)?
i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
}

i f ( a == 0) {
i f ( a == 0)
b = 10;
b = 10;
c = 10; // braces protect from
c = 10; // mistake if this
// logical mistakes
// was intended inside if } 25 / 38
Input
Object cin from iostream handles acquiring input from keyboard
operator » works with built-in types and strings objects
function get returns one character at a time
function getline returns a full line including spaces

i n t x; double d; char c;
string s ;

cin >> x ;
cin >> d ;
(Create a cpp file and test the above
cin >> c ; code with various inputs.)
cin >> s ;
getline ( cin , s ) ;

26 / 38
Input — reading from files is similar
Declare input stream of type ifstream from library fstream
“initialize it” with a file name
Alternatively use function open(filename) to open a file
use declared input stream object as you do with cin
use function eof to check for end of file
use function close when you are done reading
#i n c l u d e < fstream >
#i n c l u d e < fstream > ...
... i n t i = 0;
string line ;
ifstream ifs ( " data . txt " ) ; ifstream ifs ;
ifs . open ( " data . txt " ) ;
ifs >> x ;
w h i l e (! ifs . eof () ) {
ifs >> d ;
getline ( ifs , line ) ;
ifs >> c ; // alternatively :
ifs >> s ; // while ( getline ( ifs , line ) ) {
getline ( ifs , s ) ; cout < < " line " <<i ++ < < " : " << line ;
ifs . close () ; }
ifs . close () ;

27 / 38
Output — writing to a file
Object cout from iostream allows printing to console
Object cerr is similar but used for error messages
operator « works well with built-in types and string
string name = " John " ;
i n t yob = 1999;
d o u b l e raise = 0.12;
cout << " hello " << name << endl ;
cout << " age : " << 2019 - yob << endl ;
cout << " salary : " << (1+ raise ) *1500 << " K . L . L . " << endl ; // Allah yir7am el - lira

Writing to a file uses an ofstream object from library fstream


“initialize it” with a file name or use function open
use the declared output stream as you do with cout
use function close when you are done writing
ofstream ofs ;
ofs . open ( " result . txt " ) ; // open file for writing
ofs << " hello " << name << endl ;
ofs << " age : " << 2019 - yob << endl ;
ofs << " salary : " << (1+ raise ) *1500 << " K . L . L . " << endl ;
ofs . close () ; // now the file will be written to disk

28 / 38
Arrays — declarations
Syntax
type variable [constantsize];
type variable [constantsize]={value_1, ...,value_n};
type variable [] = {value_1, ...,value_n};
Semantics of type variable [constantsize];
Allocate constantsize type-objects consecutively in memory
let them start at address α
Allocate memory adequate to store an address and associate it with
variable
Store α in memory associated with variable

i n t a [4]={1 ,2 ,4 ,8}; // allocate an array and initialize it


c h a r c [8]={ ’h ’ , ’e ’ , ’l ’ , ’p ’ , ’ \0 ’ }; // partial in itialization
d o u b l e d [] = {1.2 , 2.6 , 3.8}; // infer size from init - list
string s [2]; // allocate two consecutive strings
cout << " addres of a : " << a << endl ;
cout << " size of a : " << s i z e o f ( a ) << " bytes " << endl ;
snapshot from ddd
cout << " size of c : " << s i z e o f ( c ) << " bytes " << endl ;
cout << " size of d : " << s i z e o f ( d ) << " bytes " << endl ;

29 / 38
Arrays — declarations, memory diagram
i n t a [4]={1 ,2 ,4 ,8}; // allocate an array and initialize it
c h a r c [8]={ ’h ’ , ’e ’ , ’l ’ , ’p ’ , ’ \0 ’ }; // partial in itializat ion
d o u b l e d [] = {1.2 , 2.6 , 3.8}; // infer size from init - list
string s [2]; // allocate two consecutive strings
cout << " addres of a : " << a << endl ;
cout << " size of a : " << s i z e o f ( a ) << " bytes " << endl ;
cout << " size of c : " << s i z e o f ( c ) << " bytes " << endl ;
cout << " size of d : " << s i z e o f ( d ) << " bytes " << endl ;

name a
value α 1 2 4 8
address α

30 / 38
Arrays — indexing
a[i] on the right hand side (read-operation)
Example: target = (a[i] + x)/2;
returns the value of the i th element of array a
eventually returns the value at address a + (i ∗ sizeof (type))
where type is the type of a’s elements
a[i] on the left hand side (write-operation)
Example: a[i] = (x+y)/2;
store the value of the right hand side expression in the i th element of a
eventually store at address a + (i ∗ sizeof (type))

31 / 38
Arrays — using arrays with a size variable
Typically we allocate a fixed size array
We need to book-keep the number of used elements
The fixed size is typically described as the capacity
The number of used elements is typically described as size
c o n s t i n t CAPACITY =16; // constant used to specify array size
i n t a [ CAPACITY ]; // pre - allocate CAPACITY elements
i n t size =0; // book - keep number of used elements in a
cout << " How big is your set ? " ;
cin >> size ;
i f ( size > CAPACITY ) {
cerr << " set is bigger than fixed size array of 16 elements " << endl ;
} e l s e { // read the elements from the user
i n t i = 0;
w h i l e ( i < size ) {
cout << " Enter element : " ;
cin >> a [ i ];
i = i +1;
}
}

32 / 38
Declaration modifiers — optional
C++ allows modifiers for declarations as follows
unsigned modifies the numeral to be non-negative
short modifies the numeral to use only two bytes
long extends the size of the numeral to more bytes depending on the
machine
long long extends the size of the numeral to be the largest supported
numeral on the platform (typically 8 bytes)
#i n c l u d e < iostream >  
#i n c l u d e < string >
u s i n g namespace std ;
> g++ -o a modifiers . cpp
i n t main () {
i n t x = -5; > ./ a
long i n t y;
long long i n t z; int :4
s h o r t i n t s; long int :8
u n s i g n e d i n t ux = -5;
cout << " int : " << s i z e o f ( x ) << endl ; long long int :8
cout << " long int : " << s i z e o f ( y ) << endl ; short int :2
cout << " long long int : " << s i z e o f ( z ) << endl ;
cout << " short int : " << s i z e o f ( s ) << endl ; int x : -5
cout << " int x : " << x << endl ; unsigned int ux :
cout << " unsigned int ux : " << ux << endl ;
4294967291
}
r e t u r n 0;
 

33 / 38
Interlude: Binary Representation

Reading a number in binary representation is similar to reading in decimal


representation, except that the base is different of course.

For example, 284 (in base 10) is read as 2 × 102 + 8 × 101 + 4 × 100 .

Similarly, (10111)2 is equivalent to


1 × 24 + 0 × 23 + 1 × 22 + 1 × 21 + 1 × 20 = 23.

34 / 38
Interlude: Binary Representation

Getting the binary representation of a number follows by successively


dividing the number by 2 and recording the remainder. Example: say we
want to represent 77 in base 2. We proceed as follows: 77=2*38+1,
hence, the least significant bit is 1. (A number is divisible by 10 if and
only if its least significant digit in decimal representation is 0. Similarly, a
number is divisible by 2 if and only if its least significant bit in binary
representation is 0).
We continue: 38=2*19+0, so the second bit is 0. 19=2*9+1, so the third
bit is 1. 9=2*4+1, so the fourth bit is 1. 4=2*2+0, so the fifth bith is 0.
2=2*1+0 so the sixth bit is 0. 1=2*0+1 so the seventh bith is 1.
So finally we got, 77 = (1001101)2 = 26 + 23 + 22 + 20 = 64 + 8 + 4 + 1.

35 / 38
Bitwise operators

C++ allows you to manipulate individual bits


Precedence is similar to Python
Always use parenthesis for clarity
Bitwise operators
Bitwise and: &, Bitwise Or: |, Bitwise not: ~
x=1+2+4; y=2+4+8+16; z=x&y; w=z|y; v=~x;
Notice 1, 2, 4, 8, and 16 are powers of two
Binary values: x : 0 . . . 0111, y : 0 . . . 011110
Results: z : 0 . . . 0110, w : 0 . . . 011111, v : 11 . . . 1000
Exercise: write a small program to do the above operations. Predict
the values of z, w , and v and check your answer by printing the values.

36 / 38
Shift operators

Operators logical left shift: « and logical right shift: »


a « b shifts binary representation of a to the left b positions
While inserting padding zeros
Similar to multiplying by 2b in case no arithmetic overflow happens
a » b shifts binary representation of a to the right b positions
While inserting padding zeros
Similar to dividing by 2b

37 / 38
Bitwise and shift operators to control bits
Set the i th bit in an integer
Perform a bitwise or with a number of all zeros and 1 at i th bit
Create that number (mask) using the left shift operator
To reset (set to 0)
Perform a bitwise and with a number of all ones and 0 at i th bit
Create that number (mask) using the left shift operator and bitwise not

// create a number with 1 at bit 5


i n t mask = 1 << 5;
i n t z = rand () ; // z could be anything
z = z | mask ; // bitwise or sets 5 th bit

// to reset use &


mask = ~(1 << 7) ; // all ones except bit 7
z = z & mask ;

38 / 38

You might also like