Beware: Hackers - (nf)

rpw3 at fortune.UUCP rpw3 at fortune.UUCP
Tue Jan 10 02:03:43 AEST 1984

fortune!rpw3    Jan  9 03:19:00 1984

"Those who learn nothing from history are doomed to repeat it"
	-- Santayana

"The only thing we learn from history is that we learn nothing
 from history" -- Hegel

"I know guys can't learn from yesterday... Hegel must be taking
 the long view" -- Brunner (as spoken by a character in Stand on Zanzibar)

Not only will "negative_int >> n"  give you a terribly wrong answer
(compared to "negative_int / (2**n)") if your machine uses logical shift,
but it will give you an "off by one" answer if you use arithmetic shift
(unless negative_int happens to be minus a power of 2 bigger than "n").

		(-5)/4 = -1	(correct integer division)

		(-5) >> 2 = -2	(arithmetic shift)

Many compilers which try to "optimize" this case also blow it (hmmm...,
you might try yours). As many have discovered in the past (the hard way,
after the compiler was in the field), the correct algorithm for optimizing
division by powers of two is (in C pseudo-code):

		if(x < 0)
		    x += 1;
		x = x "arith_right_shift" n ;	/* where the divisor is 2**n */

When the PDP-10 community was trying to make the move from the old F40
compiler to FORTRAN-10, this was a really hot issue. The new, "better"
compiler was the broken one (for a while).

Rob Warnock

UUCP:	{sri-unix,amd70,hpda,harpo,ihnp4,allegra}!fortune!rpw3
DDD:	(415)595-8444
USPS:	Fortune Systems Corp, 101 Twin Dolphins Drive, Redwood City, CA 94065

More information about the Comp.lang.c mailing list