Most efficient way to sum the 1's in a byte
Lucky
Posts: 98
I am trying to find the number of ones in a byte so that I can determine the parity bit. I have some code, but I am unsatisfied with it because I know there is a better way. Right now I'm having·a brain fart, and can't come up with anything. This is what I have:
·· index := %0000_0001
·· repeat rep from 0 to 7
····· if(KeySig &·index == 1)
········ ++parity
····· index <<= 1
·· if(parity // 2 == 1)······· 'odd parity
····· parity := 0
·· else
····· parity := 1
Is there a better way?
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
"You do not really understand something unless you can explain it to your grandmother."
-Lucky[size=-1][/size]
Post Edited (Lucky) : 4/3/2010 12:57:58 AM GMT
·· index := %0000_0001
·· repeat rep from 0 to 7
····· if(KeySig &·index == 1)
········ ++parity
····· index <<= 1
·· if(parity // 2 == 1)······· 'odd parity
····· parity := 0
·· else
····· parity := 1
Is there a better way?
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
"You do not really understand something unless you can explain it to your grandmother."
-Lucky[size=-1][/size]
Post Edited (Lucky) : 4/3/2010 12:57:58 AM GMT
Comments
Edit: minor improvement
Edit: and one more
Post Edited (kuroneko) : 4/3/2010 4:35:39 AM GMT
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
"You do not really understand something unless you can explain it to your grandmother."
-Lucky[size=-1][/size]
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
*Peter*
Does that make sense?
In assembler the carry holds the parity value when ANDing the long with $FFFF_FFFF. That of course is the same as the slightly more convenient form of ANDN Long, #0 ..... so a single instruction.
But that's assembly..... unfortunately I don't (yet) know or understand SPIN, and can't help you there.
Cheers,
Peter (pjv)
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Jon McPhalen
Hollywood, CA
@pjv: how do you know assy but not spin, I thought every program on the prop needed some spin
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
"You do not really understand something unless you can explain it to your grandmother."
-Lucky[size=-1][/size]
I ran some benchmark speed test on the suggested methods...
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Beau Schwabe
IC Layout Engineer
Parallax, Inc.
Bill
For speed testing, just set up the routine to be timed in a repeat loop that toggles a pin !outa[noparse][[/noparse]0]
Use this routine as a baseline time, use a scope to measure the width of the pulse.
Now, do the same thing by adding the code you want to time and use a scope to measure the width of that pulse.
To isolate just how long the timed routine requires, subtract the baseline amount of time from the time with the added code.
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Beau Schwabe
IC Layout Engineer
Parallax, Inc.
I like the way you think. Teach a man to fish...
Roger
Use a convenient loop count that you can easily measure with a watch.
Hacker's Delight devotes 25 pages to functions based on counting 1s.
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Tracy Allen
www.emesystems.com