Efficient way to reverse a byte?
Russell McMahon email (remove spam text)
The piece of code that Tracy posted (from John Payson) does what it was
originally meant to do BUT is NOT correct for the present problem.
Here we require
76543210 --> 01234567
John's solution is for a 7 bit swap ignoring B7.
ie x6543210 --> x0123456
As a consequence B7 & B3 is untouched and there are only 3 swaps needed
making the code shorter.
Rewriting it for an 8 bit swap as required here, produces -
17 instructions, time varies depending on data but fairly quick.
Operation may not be initially obvious.
For N = 0 to 3
If bN = 1 then invert bits bN and b(7-N)
If b(7-N) = 1 then invert bits bN and b(7-N)
Worst case, if both bits in a pair are set it inverts them both twice.
Best case, if neither is set it takes no action.
This suggests that a more cunning test for "both bits set" may allow a small
reduction in run time but intuition suggests that the testing overhead would
John's solution is elegant but a little hard on the brain.
I prefer Dwayne Reids more brute force -
because it's much easier for trhe average person to see what is happening at
a glance (or a few glances :-) - YMMV).
A full 8 bit lookup table is much quicker and much much less code space
A dual nibble lookup table is not much quicker on average and rather less
Lookup tables have the possible advantage of having a constant
>From another world - http://www.easttimor.com
What can one man* do?
Help the hungry at no cost to yourself!
(* - or woman, child or internet enabled intelligent entity :-))
From: Tracy Smith <YAHOO.COM> dot_lo
See also: www.piclist.com/techref/index.htm?key=efficient+way+reverse
You must be a member of the
piclist mailing list
(not only a www.piclist.com member) to post to the