You are on page 1of 26

Introduction to Programming

Lecture 21
Today’s Lecture

 Bit manipulation
 Bit operators
Logical Operators

AND &&
OR ||
Bit manipulation operators
& Bitwise AND Operator
| Bitwise OR Operator
^ Bitwise Exclusive OR Operator
~ NOT Operator
<< Left Shift Operator
>> Right Shift Operator
Bitwise AND Operator
Truth table for AND operation

Bit1 Bit2 Bit1 & Bit2


1 1 1
1 0 0
0 1 0
0 0 0
Bitwise AND Operator Example
3 2 1 0
………… 2 2 2 2
12 = 1 1 0 0
&
8 _______________
= 1 0 0 0
1 0 0 0

Hence x = 12 & 8 = 8
Example
#include <iostream.h>
main ( )
{
int number = 12 ;
if ( number & 0x8 )
cout << "Bit number four is set" << endl ;
else
cout << "Bit number four is not set" << endl ;
}
Bitwise OR Operator
Truth table for OR operation
A B A|B
1 1 1
1 0 1
0 1 1
0 0 0
Bitwise OR Operator
Example 1
X = 12 | 8

1 1 0 0
|
1 0 0 0
_____________
1 1 0 0
Hence the result x = 12
Bitwise OR Operator
Example 2
x=8|1
1 0 0 0
|
0 0 0 1
_____________
1 0 0 1

Hence the result x = 9


Bitwise Exclusive OR
Operator
Truth table for Exclusive OR operation
A B A^B
1 1 0
1 0 1
0 1 1
0 0 0
Example: Exclusive OR
Operator
X=8^1
1 0 0 0
0^ 0 1
0_____________
Result x = 9 1 0 0 1

X=9^1 0 0 ^0 1
_____________
Result x = 8 1 0 0 0
NOT Operator

Truth table for NOT operator

A ~A
0 1
1 0
NOT Operator

x=8
~ ( 1000 ) = 0111
= 7
Bit Flags
Read Write And Execute
Exclusive OR Operator
Example
unsigned int a , b , c ;
a = 112 ;
b = 32 ;
c=a^b;
c = ( a ^ b ) ^ b ; the result is a
c = ( a ^ b ) ^ a ; the result is b
Raid
Redundant Array of Inexpensive Devices
Hot Plug
Example
Swapping two integers without
a temporary storage

unsigned int a = 12 ;
unsigned int b = 8 ;

a=a^b;
b=b^a;
a=a^b;
Unsigned integer

unsigned int i , j , k ;
Left Shift
A number 1
Shift left
Right Shift
A number 10
Right shift

10

01
Left & Right Shift
Operator

 << shift left


 >> shift right
Left & Right Shift
Operator
Unsigned int i = 4 ;
i << 1 ; shift left
i >> 1 ; shift right
Left shift
1 0 1 1 0 0 0 1

Right shift
1 0 1 1 0 0 0 1

You might also like