Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!decwrl!purdue!gatech!mcnc!rti!trt From: trt@rti.UUCP (Thomas Truscott) Newsgroups: comp.unix.questions Subject: Re: Bit Switching - How? Summary: Bit swapping Keywords: bits, flip Message-ID: <2872@rti.UUCP> Date: 4 Apr 89 15:23:56 GMT References: <1138@uvm-gen.UUCP> Distribution: usa Organization: Research Triangle Institute, RTP, NC Lines: 20 > Does anyone know of a *very fast* way to swap bits at some location n > between two separate bytes b1 and b2? Suppose "mask" is a mask of the bits you want swapped (e.g. to swap the 3rd (4-valued) bit the mask would be 0x04). Then the following will swap the "mask"ed bits of b1 and b2: t = (b1 ^ b2) & mask; b1 ^= t; b2 ^= t; Depending on your machine this may be faster than any table lookup. Of course *very fast* means you should (a) scrutinize the compiler's assembly output and (b) ponder your machine's instruction set repertoire to ensure you are not wasting cycles. (E.g. does your machine have an XOR instruction? Is it a fast instruction? How should "t" be declared? Do you need to declare it "register"? Which is faster, "& mask" or "& ~mask"? And so on.) Tom Truscott