Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!ncar!oddjob!gargoyle!att!ttrdc!levy From: levy@ttrdc.UUCP (Daniel R. Levy) Newsgroups: comp.lang.c Subject: Re: Shifting question Message-ID: <2813@ttrdc.UUCP> Date: 20 Jul 88 04:01:21 GMT References: <705@bnr-rsc.UUCP> <11556@steinmetz.ge.com> <60290@sun.uucp> <1818@spar.SPAR.SLB.COM> Organization: AT&T, Skokie, IL Lines: 70 In article <1818@spar.SPAR.SLB.COM>, hunt@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>= count; } else if (count < 0) { count = -count; for (j=0; j