Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!decwrl!decvax!ima!cfisun!lakart!dg From: dg@lakart.UUCP (David Goodenough) Newsgroups: comp.unix.questions Subject: Re: Bit Switching - How? Message-ID: <486@lakart.UUCP> Date: 10 Apr 89 16:21:28 GMT References: <2345@van-bc.UUCP> Organization: Lakart Corporation, Newton, MA Lines: 27 From article <2345@van-bc.UUCP>, by sl@van-bc.UUCP (pri=-10 Stuart Lynne): > 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? > > For fast generic swapping I use: > > #define swap(a,b) {a^=b;b^=a;a^= b;} I think Mr. Wirthlin is after something that will leave all bits alone, except it will swap (for example) bit 2 between the bytes. I submit the following extension to Mr. Lynne's macro: #define swap(a, b, n) ((a) ^= ((b) & (n)), (b) ^= ((a) & (n)), \ (a) ^= ((b) & (n))) where n is a mask of bits to be swapped. This can also be used in expressions returning the final value of a. Of course if you want to explicitly swap bit 2 or bit 5, i.e. give the bit by number: #define swapn(a, b, x) swap((a), (a), (1 << (x))) -- dg@lakart.UUCP - David Goodenough +---+ IHS | +-+-+ ....... !harvard!xait!lakart!dg +-+-+ | AKA: dg%lakart.uucp@xait.xerox.com +---+