Path: utzoo!attcan!uunet!lll-winken!lll-tis!helios.ee.lbl.gov!pasteur!ucbvax!decwrl!spar!hunt From: hunt@spar.SPAR.SLB.COM (Neil Hunt) Newsgroups: comp.lang.c Subject: Re: Shifting question Message-ID: <1818@spar.SPAR.SLB.COM> Date: 19 Jul 88 20:48:34 GMT References: <705@bnr-rsc.UUCP> <11556@steinmetz.ge.com> <60290@sun.uucp> Reply-To: hunt@spar.UUCP (Neil Hunt) Organization: SPAR - Schlumberger Palo Alto Research Lines: 51 In article <60290@sun.uucp> guy@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@spar.slb.com ...{amdahl|decwrl|hplabs}!spar!hunt