; ; CPE 221 Assembly Example ; ; This program counts the number of ones in a variable. ; #include ; using namespace std; ; ; int main() ; { ; int count = 0; ; int bits = 0; ; int temp; ; int num = 4592; ; while (num != 0) ; { ; temp = num & 1; ; if (temp != 0) ; { ; count++; ; bits++; ; } ; num = num >> 1; ; } ; return 0; ; } .org 200 count: .dw 1 ; reserve space for result bits: .dw 1 ; reserve space for number of bits examined num: .dc 0 ; The variable to be examined. mask: .dc 1 ; Mask used to look at only bit 0 of a register. orig: .org 1000 lar r30, done lar r29, shift lar r28, next ld r1, num ; Load variable into r1. ld r3, mask ; Load mask into r3. sub r2, r2, r2 ; r2 accumulates number of 1s, initialize to 0. sub r5, r5, r5 ; r5 accumulates number of bits, initialize to 0. brzr r30, r1 ; If r1 is zero, there are no 1s in num. next: and r4, r1, r3 ; And r1 with mask, put in r4. addi r5, r5, 1 ; Increment number of bits. brzr r29, r4 ; If r4 is 0, the bit was zero, look at next bit. addi r2, r2, 1 ; If r4 is non-zero, the bit was 1, increment r2. shift: shr r1, r1, 1 ; Shift r1 right to look at next bit. brnz r28, r1 ; If r1 is non-zero, and with mask. done: st r2, count ; r1 = 0 means done, store r2 into count. st r5, bits ; Store r5 into bits. stop