Shifting question

Daniel R. Levy levy at ttrdc.UUCP
Wed Jul 20 14:01:21 AEST 1988


In article <1818 at spar.SPAR.SLB.COM>, hunt at spar.SPAR.SLB.COM (Neil Hunt) writes:
# 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 !!

To be perfectly honest, please note that the factor of two can be in code
size rather than execution time.  (See below.)  My guess, having studied a
few machine architectures, is that C is bringing you close to the hardware
on this issue.  Some machines don't implement "negative shift."  If C were
required to support a "negative shift" the compiler would have to work
around the problem anyway on computers that don't implement such a shift,
and a programmer usually has a better idea of what kind of tradeoff (code
space versus execution time) to make in the workaround than the compiler
does.

	register int r,c,i,j;
	register PIXEL **p;

	if (count == 0) return;

	c = image->cols;
	r = image->rows;
	p = image->pixels;

	if (count > 0) {
		for (j=0; j<r; j++)
			for (i=0; i<c; i++)
				p[i][j] >>= count;
	} else if (count < 0) {
		count = -count;
		for (j=0; j<r; j++)
			for (i=0; i<c; i++)
				p[i][j] <<= count;
	}
-- 
|------------Dan Levy------------|  THE OPINIONS EXPRESSED HEREIN ARE MINE ONLY
|    AT&T  Data Systems Group    |  AND ARE NOT TO BE IMPUTED TO AT&T.
|        Skokie, Illinois        | 
|-----Path:  att!ttbcad!levy-----|



More information about the Comp.lang.c mailing list