Using Loops and Indexed Addresses to Calculate Array Sum parity
Solution
.data
@ Array of digits for the number: 98912
digits: .word 9,8,9,1,2
result: .asciz "Sum with parity of 9,8,9,1,2 = %d\n"
.text
.global main
main:
PUSH {R4-R6, LR} @ save registers and LR on the stack
@ calculating array sum
MOV R0, #0 @ initialize sum to zero
LDR R1, =digits @ point to start of the array
MOV R2, #0 @ start array index in zero
loop1:
LDR R3, [R1, R2, LSL #2] @ load element from array
ADD R0, R0, R3 @ add element to the total sum
ADD R2, R2, #1 @ increment index
CMP R2, #5 @ see if all digits have been added
BLT loop1 @ repeat until all digits have been added
@ calculate parity
MOV R4, R0 @ save sum in R4
BL parity @ calculate sum parity
@ add parity to sum
LSL R4, R4, #1 @ shift left to add a parity bit
ORR R4, R4, R0 @ add parity bit at the lowest position
@ print result
LDR R0, =result @ put string to print in R0
MOV R1, R4 @ put result in R1
BL printf @ print result on the screen
MOV R0, R4 @ we leave the result of sum+parity in R0
POP {R4-R6, LR} @ restore registers and LR from the stack
MOV PC, LR @ return to caller
@ Subroutine to calculate the parity of a number given in R0,
@ returns parity in R0
parity:
PUSH {LR} @ save return address
MOV R1, #0 @ initialize parity to zero
loop2:
ANDS R2, R0, #1 @ test lowest bit
EOR R1, R1, R2 @ update parity using the bit
LSR R0, R0, #1 @ shift right to test next bit
CMP R0, #0 @ see if the number to tests is zero
BNE loop2 @ if not zero, keep calculating parity
MOV R0, R1 @ return the calculated parity
POP {LR} @ restore return address
MOV PC, LR @ return to caller