Page 36 - DCAP404 _Object Oriented Programming
P. 36
Unit 2: Beginning of OOP Language
2.3.5 Shift Operators Notes
Data is stored internally in binary format (in the form of bits). A bit can have a value of one or
zero. Eight bits form a byte. The following displays the binary representation of digits 0 to 8.
Decimal Binary Equivalent
0 00000000
1 00000001
2 00000010
3 00000011
4 00000100
5 00000101
6 00000110
7 00000111
8 00001000
Shift operators work on individual bits in a byte. Using the shift operator involves moving the
bit pattern left or right. You can use them only on integer data type and not on the char, bool,
float, or double data types.
Operator Description Example Explanation
>> Shifts bits to the right, a=10 >> 3 The result of this is 10 divided
filling sign bit at the left by 23. An explanation follows.
<< Shifts bits to the left, a=10 << 3 The result of this is 10
filling zeros at the right multiplied by 23. An
explanation follows.
Example:
#include <iostream>
using namespace std;
int main() {
cout << “5 times 2 is “ << (5 << 1) << endl
<< “20 divided by 4 is “ << (20 >> 2) << endl;
}
Shifting Positive Numbers
If the int data type occupies four bytes in the memory, the rightmost eight bits of the number 10
are represented in binary as
0 0 0 0 1 0 1 0
When you do a right shift by 3(10 >> 3), the result is
0 0 0 0 0 0 0 1
LOVELY PROFESSIONAL UNIVERSITY 29