#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2008
    Posts
    9
    Rep Power
    0

    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.
  2. #2
  3. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    You can repeatedly AND the number with 1, then right-shift it and do it again.

    -Dan
    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.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2010
    Location
    Hampshire, UK
    Posts
    11
    Rep Power
    0
    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
    LOOP:
    SHLC A ; shift A left through carry
    JRNC NOADD
    INC B ; count this bit
    NOADD:
    DEC C ; next bit
    JRNZ LOOP

IMN logo majestic logo threadwatch logo seochat tools logo