Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!dali.cs.montana.edu!caen!zaphod.mps.ohio-state.edu!swrinde!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.jpl.nasa.gov (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: flipping bits in perl Message-ID: <1991May31.184927.167@jpl-devvax.jpl.nasa.gov> Date: 31 May 91 18:49:27 GMT References: <1991May30.231900.12417@com50.c2s.mn.org> <1991May31.162709.7069@iWarp.intel.com> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 40 In article <1991May31.162709.7069@iWarp.intel.com> merlyn@iWarp.intel.com (Randal L. Schwartz) writes: : In article <1991May30.231900.12417@com50.c2s.mn.org>, caa@com50 (Charles Anderson) writes: : | : | Yesterday a coworker asked me if I could flip all of the bits in the : | font file he was using, and I decided to try using perl to do it. : | (I could easily do it in C but I'm trying to learn perl and thought : | I'd give it a go.) I tried all sorts of things tr/\000-\377/\377-\000/ You can't give negative ranges like \377-\000. You could construct one and eval it, however. : | didn't work neither did s/./~$&/g in various type of things. I even You'd have to say pack(C,~unpack(C,$&)), or some such. : | tried unpacking it into an array and flipping from there but that wasn't : | very succesful either. I but a vec() into the code (something like : | vec("blah", 0, 1) to see if the bit twiddling would start working after : | that but it didn't. I'm stumped...anybody know how to do it. All I : | really want is a bit negation or xor $ff. : : Here's a really awfully fast program hand-tuned by Larry and me while : we were one-upping each other while writing the book. It does exactly : what you asked for. *How* it does it should be a useful puzzle to : figure out... : : #!/usr/bin/perl : $bufsize = 16384; : vec($ones,0,8) = 255; : $ones x= $bufsize; : while(read(STDIN,$_,$bufsize)) { : print STDOUT length != $bufsize ? : substr($_ ^ $ones, 0, length) : $_ ^ $ones; : } Note that there's a bug in vector ^ (in 4.003) that may prevent this from working. It might work to use the assignment operator, $_ ^= $ones, however. Larry