Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cornell!uw-beaver!mit-eddie!ll-xn!husc6!cmcl2!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn ) Newsgroups: comp.unix.questions Subject: Re: Bit Switching - How? Keywords: bits, flip Message-ID: <9977@smoke.BRL.MIL> Date: 4 Apr 89 08:40:57 GMT References: <1138@uvm-gen.UUCP> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 20 In article <1138@uvm-gen.UUCP> wirthlin@uvm-gen.UUCP (Ralph Wirthlin) writes: >Does anyone know of a *very fast* way to swap bits at some location n >between two separate bytes b1 and b2? The answer must of course depend on architectural and language implementation details. One very fast way is to directly index the result in a table a la b1_swapped = b_table[b1][b2][offset]; b2_swapped = b_table[b2][b1][offset]; where of course the tables have been preinitialized with the correct answers. If you don't have space for such a large table (512Kbytes, assuming 8-bit bytes) then a compromise solution that generally takes longer but uses a tiny table is b1_bit = b1 & mask[offset]; b2_bit = b2 & mask[offset]; b1 = b1 & ~mask[offset] | b2_bit; b2 = b2 & ~mask[offset] | b1_bit; with suitable optimization. If your processor has a very speedy shift operator then replace mask[offset] with (1<