ON 20051011@2:07:13 PM at page: http://www.piclist.com/microchip/math/bit/revbits.htm#38636.4633449074 James Newton[JMN-EFP-786] published post 38636.4633449074 haggart@slac.stanford.edu
I'm totally new at this and I haven't yet tested my code, but I came up with this concept for word reversal before discovering this page and I can't see why it wouldn't work. It is for a PIC 16F870 with 4MHz crystal. It takes 2n+1 instructions, n being the number of bits you want to change, and one register file large enough to hold them.

The idea is to first clear all bits (assign a value of 0) in the target word (the one which will end up reversed). You then use the PIC's bit test instruction (btfsc) to check each bit of the source word one at a time, to see if that bit is already a zero. If it is, you skip the next instruction, which is an unconditional bit set (bsf) pointing to the desired bit of the target word. Since you started out by filling the target word with 0s, you only need to use the bit-set instruction on those bits in the source word that contain 1s. And since each of these instructions is bit-specific, you can stuff the bits into the target word in any order you want, allowing word-reversal. My code is:

clrf targetword
btfsc sourceword,7
bsf targetword,0
btfsc sourceword,6
bsf targetword,1
btfsc sourceword,5
bsf targetword,2
btfsc sourceword,4
bsf targetword,3
btfsc sourceword,3
bsf targetword,4
btfsc sourceword,2
bsf targetword,5
btfsc sourceword,1
bsf targetword,6
btfsc sourceword,0
bsf targetword,7; the register "targetword" now contains a reversed version of the register "sourceword"

It seems to me that the execution speed will depend on the number of 1s and 0s in the source word. If you know that it's likely to contain more 1s than 0s most of the time, you could probably speed it up by first setting the target word to all 1s instead of all 0s, then using the btfss and bcf instructions instead of the btfsc and bsf instructions as above. The concept is the same.

It also seems to me that this scheme can be used to create an ordered byte out of randomly-assigned I/O pins, making it easier to do board layouts. But again, I'm a complete newbie at this and I might be missing something. Please let me know if I am!

-Craig Haggart
Sunnyvale, California
haggart@slac.stanford.edu
|Delete 'P-' before: '' but after: '