View Full Version : Counting bits
RussMartin
- 10th October 2008, 07:45
Does anyone know a quick and easy (or sneaky) way to count bits?
I want to look at either the top or bottom 4 bits of a word and determine whether an odd or even number of bits are high (or low; doesn't matter).
Right now, I'm using LOOKDOWN and it works just fine; but I keep thinking there's a more elegant way to do it.
Darrel Taylor
- 10th October 2008, 08:47
Hi Russ,
Not particularly "Sneaky" ... but it's "Quick".
Counter VAR BYTE BANK0
ODD VAR Counter.0
TestWord VAR WORD BANK0
ASM
clrf _Counter
btfsc _TestWord,0
incf _Counter, F
btfsc _TestWord,1
incf _Counter, F
btfsc _TestWord,2
incf _Counter, F
btfsc _TestWord,3
incf _Counter, F
ENDASM
If ODD THEN
; ODD number of bits in the TestWord<3:0>
ENDIF
Acetronics2
- 10th October 2008, 09:03
Hi, Russ
first, shift right your word 12 times if > 4095 ...
mask the result to keep the 4 lower bits,
then 6 possibilities remain for an even count of the bits ...
( call the result "ABCD" ... if even, ABCD = Ch,Ah,9h,6h,5h or 3h )
A SELECT CASE will do it.
mask your word to keep the 4 lower bits
Then 6 possibilities ...
The SELECT CASE ...
it's one way ...in PbP !!! ( lol )
or use "NCD" function in a loop ... which looks furiously to what Darrel Wrote !!!
Alain
RussMartin
- 10th October 2008, 23:20
Thanks to both of you.
I'm emulating a 16-bit twisted ring counter--actually a very twisted counter. If an even number of bits in the top four are high, the whole works is shifted left one place and the lowest bit is set to 1; if an odd number of bits are high, again a one-place shift left, but the default 0 shifted in is retained.
Just now, the target device is a 16F87xA.
Powered by vBulletin® Version 4.1.7 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.