Hello. I have following question, can someone explain to me, how I can
shift left some value using only pen and paper? Or is there some clever
way without playing with binary numbers at all?
"After execution of the final assignment to ByteVal, what will be the
numeric value of X?
void main()
{
unsigned char X=7;
X<<= 4;
}
A) 28
B) 11
C) 112
D) 56
"
In addition to all the methods mentioned by the other responders, there
is another way which seems the most straightforward to me.
Double the number as many times as the shift value counts, in this case:
7 << 4 = 7 * 2 * 2 * 2 * 2 =
14 * 2 * 2 * 2 =
28 * 2 * 2 =
56 * 2 = 112
Replace "double" with "halve" for the right shift:
112 >> 4 = 112 / 2 / 2 / 2 / 2 =
56 / 2 / 2 / 2 =
28 / 2 / 2 =
14 / 2 = 7
If you get any decimal on the way simply discard it - for example:
113 >> 4
113, 56.5000, 28.2500, 14.1250, (7.0625 ==> 7)
or easier and faster:
113, (56.5 ==> 56), 28, 14, 7
[ digression
Here is some "Zen" method to calculate left shifts.
With one sheet of paper:
- ply it zig-zag 6 times (7-1) so that you get 7 "columns"
- open all the plies and flatten the sheet out again
- ply it in halves 4 times, following the perpendicular to the first
plies (that is, follow the "rows" direction, since the others were the
"columns").
Flattening out the sheet again and counting the "cells" will give the
result of the shift.
Plying a sheet of paper in halves more than three / four times, though,
can be a tough work, especially if the sheet is small and the paper is
heavy (thick).
-
With strings: take seven equally-long strings and tie them together with
a knot at half of their length, then group together the loose ends, add
another knot halfway through, regroup the endings and so on, four knots
in total.
Counting the "segments" (the strings going from knot to knot plus those
from the last knot to the loose ends) will give the result of the shift.
Also here, making a knot on a 56-strings "wire" can become a difficult
task, better to use long and thin strings.
-
Of course, the above methods can be improved by using multiplications
(rows * columns instead of counting cells, for example) but then it's
better to do this all by using just mathematics ;-)
By the way, I don't know any "Zen" way to calculate right shifts, can
anybody point out one?
end digression ]