Shifting question

Neil Hunt hunt at spar.SPAR.SLB.COM
Wed Jul 20 06:48:34 AEST 1988


In article <60290 at sun.uucp> guy at gorodish.Sun.COM (Guy Harris) writes:
>	7.5 Shift operators
>	...
>	The result is undefined if the right operand is negative, or greater
>	than or equal to the length of the object in bits.
>ANSI C:
>	3.3.7 Bitwise shift operators
>	...If the value of the right operand is negative or is greater than or
>	equal to the width in bits of the promoted left operand, the behavior
>	is undefined.

This has been a pet peeve of mine for a long time: does the following function
work for applying a shift (left or right) to all pixels in a large image ?

shift_pixel(image, count)
struct image *image;
int count;
{
	int i, j;

	for(j = 0; j < image->rows; j++)
		for(i = 0; i < image->cols; i++)
			image->pixels[i][j] >>= count;
}

No, it doesn't; the last line has to be:

			if(count > 0)
				image->pixels[i][j] >>= count;
			else
				image->pixels[i][j] <<= -count;

because of the stupid undefined rule about shifts.

An alternative solution is

	rshift = count > 0 ? count : 0;
	lshift = count < 0 ? -count : 0;

	for(j = 0; j < image->rows; j++)
		for(i = 0; i < image->cols; i++)
			image->pixels[i][j] =
			  ((image->pixels[i][j] >> rshift) << lshift);

We are talking factors of two in execution time for these functions.
What a pain !!

Neil/.
-- 

	hunt at spar.slb.com
     ...{amdahl|decwrl|hplabs}!spar!hunt



More information about the Comp.lang.c mailing list