Bit Switching - How?

David Goodenough dg at lakart.UUCP
Tue Apr 11 02:21:28 AEST 1989


>From article <2345 at van-bc.UUCP>, by sl at van-bc.UUCP (pri=-10 Stuart Lynne):
> In article <1138 at uvm-gen.UUCP> wirthlin at 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 at lakart.UUCP - David Goodenough		+---+
						IHS	| +-+-+
	....... !harvard!xait!lakart!dg			+-+-+ |
AKA:	dg%lakart.uucp at xait.xerox.com		  	  +---+



More information about the Comp.unix.questions mailing list