86 Introduction to C++ Programming and Graphics
Shift operators
The commands:
short a=50;
short b;
b=a<<3;
cout << a << ", " << b << endl;
print on the screen:
50, 400
We note that the binary representation of 400 is:
0000000110010000
and conclude that the statementa<<3causes the binary string ofato be
shifted to the left by three places.
More generally, the statementa<<mcauses the binary string ofato be
shifted to theleftbymplaces. The statementa>>mcauses the binary string
ofato be shifted to therightbymplaces. When the binary string is shifted
to the left or to the right bymplaces, the numberais multiplied or divided by
2 m. Accordingly,<
βandβ operator
The statements:
short a=50;
shortb=a<<3;
cout << "a=" << a << " b=" << b << endl;
shortc=a&b;
cout << "c=" << c << endl;
print on the screen:
a=50 b=400
c=16
To understand thec=a&boperation in the penultimate line of the code, we
consider the binary representation of the three numbers involved,