Bit Switching - How?

pri=-10 Stuart Lynne sl at van-bc.UUCP
Wed Apr 5 10:27:30 AEST 1989


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;}

This method has the advantage of not needing any temporary variable. So if
your arg's are in registers it reduces to three XOR instructions.

Be sure to implement as a macro, procedure call overhead would dwarf
everything else if you didn't.

Adding masks so that it only handles bits is left as an exercise for the 
reader :-)

-- 
Stuart.Lynne at wimsey.bc.ca uunet!van-bc!sl 604-937-7532(voice) 604-939-4768(fax)



More information about the Comp.unix.questions mailing list