October 20th, 2009, 06:48 PM
Counting 1's in 16 bit word
I am trying to count the number of 1's in a sixteen bit word for MC68HC12. The only way I can think of is to use 16 BITA instructions, one for each bit location, then increment a counter. I suspect there is a more elegant way to do this. Could someone share their ideas with me.
October 21st, 2009, 03:52 PM
You can repeatedly AND the number with 1, then right-shift it and do it again.
HEY! YOU! Read the New User Guide and Forum Rules
"They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin
"The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002
Think we're being rude? Maybe you asked a bad question
or you're a Help Vampire.
Trying to argue intelligently? Please read this.
March 26th, 2010, 09:34 AM
Shift the register through the carry bit, if the carry is set then increment another register
; assembler psuedo code (makes no assumptions about register size)
; if the register are less than 16 bits then you will have to put the test value into the accumulator in to parts or use multiple registers.
; value in to test in A
LD B,0 ; bit counter
LD C,16 ; loop counter
SHLC A ; shift A left through carry
INC B ; count this bit
DEC C ; next bit