Bit Switching - How?
Doug Gwyn
gwyn at smoke.BRL.MIL
Tue Apr 4 18:40:57 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?
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<<offset), but first check
that 1<<0 works (I once ran into a processor where it didn't).
More information about the Comp.unix.questions
mailing list