2011-11-17
Currently, I read ``Compilerbau'' by Niklaus Wirth (in German).
The book's very old (1977), but still worthwhile, even though
it's all Pascal syntax.
The book shows the following multiplication function:
procedure multiply;
var a, b;
begin a := x; b := y; z := 0;
while b > 0 do
begin if odd b then z := z + a;
a := 2*a; b := b/2;
end
end;
(The global variables x and y are the factors, z is the result.)
My first though had been: ``Strange!''
But let's get rid of the Pascal syntax and convert it to C style:
int
multiply(int a, int b)
{
int z = 0;
while (b > 0) {
if (b % 2 == 1) {
z += a;
}
a *= 2;
b /= 2;
}
return z;
}
Well, it's still strange ... but wait, remember assembler pro-
gramming:
int
multiply(int a, int b)
{
int z = 0;
while (b > 0) {
if (b & 1) {
z += a;
}
a <<= 1;
b >>= 1;
}
return z;
}
All those operations are fast on the machine level. That's the
reason for doing it this way.
It had been interesing to find this out, but I'm too young to
have lived in this world myself.
http://marmaro.de/lue/ markus schnalke