- ARM

ARM assembly code to find number of ones and zeros in a 32 bit number

Hello guys! Today we will see how to find number of ones and zeros in a 32 bit number. Let’s first understand the algorithm later we see a example code.
Algorithm:

  1. Start
  2. Store a 32 bit number in register(Rd).
  3. Initialize a counter register to 1Fh(32)
  4. Initialize one regiter(Ra) to zero to store number of ones, and another register(Rb) to zero to store number of zeros.
  5. Right rotate the number through carry
  6. If carry is set
    • Increment Ra.
  7. Else
    • Increment Rb.
  8. Decrement counter value by 1.
  9. Repeat steps 5-8 till counter value reaches 32.
  10. Stop

Here is a example code to find number of ones and zeros in a 32 bit number
Code:
 

 AREA program,CODE,READONLY
      ENTRY
      MOV R0,#0x12345678  ; Register Rd
      MOV R1,#1F          ; Counter register
label MOVS R0,R0,LSR #1   ; Logical right shift of number
      ADDCS R3,R3,#1      ; R3 holds number of ones
      ADDCC R4,R4,#1      ; R4 holds number of zeros
      SUB R1,R1,#1        ; decrementing counter value
      CMP R1,#00
      BNE label
      END

Leave a Reply