Easy way to count the number of 1's in a long?
Rayman
Posts: 14,825
Ok, so I have two longs and I want to count the total number of binary 1's in both of them.
It seems that there should be a direct way to do it in Spin, but it escapes me...
In my particular problem the result is between 0 and 8. (Chess bitboard)
I'm thinking that a look with the Spin "bitwise encode" operator will be the fastest method of doing this.
But, I have a feeling that I'm missing something...
Anybody see a simple way to do this?
It seems that there should be a direct way to do it in Spin, but it escapes me...
In my particular problem the result is between 0 and 8. (Chess bitboard)
I'm thinking that a look with the Spin "bitwise encode" operator will be the fastest method of doing this.
But, I have a feeling that I'm missing something...
Anybody see a simple way to do this?
Comments
mov sample, temp1
mov temp2, #32
mov temp3, #0
loop: shr temp1, #1 wc
if_c add temp3, #1
djnz temp2, #loop:
the result will be in temp3
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Parallax Forums - If you're ready to learn, we're ready to help.
It chunks the long into 4-bit blocks and adds the results from a pre-computed lookup table for each of them.
-Phil
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
'Still some PropSTICK Kit bare PCBs left!
Post Edited (Phil Pilgrim (PhiPi)) : 8/30/2008 3:27:42 AM GMT
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Parallax Forums - If you're ready to learn, we're ready to help.
but x &= x-1 is much niftier. There is also,
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Tracy Allen
www.emesystems.com
Post Edited (MikeK) : 8/30/2008 2:14:50 PM GMT
If you do unroll my loop, create an array of bytes in the DAT area and index them, instead of using LOOKUPZ, to save memory.
Tracy,
Wow! A log n solution. I knew there had to be a way but couldn't quite get there. Guys, if you haven't yet taken the time to understand Tracy's second method, do so now. It's a work of art!
-Phil
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
'Still some PropSTICK Kit bare PCBs left!