Bit Switching - How?
Thomas Truscott
trt at rti.UUCP
Wed Apr 5 01:23:56 AEST 1989
> 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
More information about the Comp.unix.questions
mailing list