简体   繁体   中英

How do I write a LC-3 assembly code for finding the maximum of a list?

Write a LC-3 assembly code for finding the maximum of a list of positive numbers in memory. R0 contains the location in memory of the start of the list, and the end of the list of numbers is signified by a zero or negative number. The code should place the greatest of the values in the list into register R5. If the first number of the list is zero or negative, R5 should contain zero. For example, if R0 contains the value x4000, and the memory contains the following values: x4000: 10 x4001: 20 x4002: 15 x4003: -1

The problem says there's an example in the book but I found nothing helpful, I wrote some code for the problem before,

.orig x3000

           LD R1, NUMBER1    ;load NUMBER1 into R1
           LD R2, NUMBER2    ;load NUMBER2 into R2

           BRz Equals        ;we jump to Equals if NUMBER1 = NUMBER2  (we can just jump directly to END)
           BRn GreaterR2     ;we jump to GreaterR2 if NUMBER1 < NUMBER2
           BRp GreaterR1     ;we jump to GreaterR1 if NUMBER1 > NUMBER2

Equals     BRnzp End         ;

GreaterR2  ADD R5, R5, #2   ;R0 = -1
           BRnzp End

GreaterR1  ADD R5, R5, #6    ;R0 = 1
           BRnzp End

End    HALT               ;THE END


NUMBER1 .FILL #2              ;
NUMBER2 .FILL #6              ;

.END

So I have this but after I have no idea how to do a list. Could I get some help?

Your list is really a null terminated array of numbers. You can declare memory space with BLKW followed by the number of words you want to reserve

list: .BLKW 1000

You can read from this memory by getting the address of list with LEA, storing and incrementing a counter variable then loading the memory into a register with LDR.

.orig x3000 AND R0, R0, #0 ; Clear R0 LEA R1, N1 ; R1 is a pointer to N1 LDR R5, R1, #0 ; R5 is the max Loop
LDR R2, R1, #0 ; load numbers into R2 ADD R1, R1, #1 ; Increment pointer

ADD R2, R2, #0 BRz Exit ; Jump to Exit if number is cero BRn Exit ; Jump to Exit if number is negative

; number is positive, so check which is max
AND R3, R3, #0 ; Clear R3 ADD R3, R2, #0 ; Calc 2-complement
NOT R3, R3 ADD R3, R3, #1 ADD R6, R3, R5 BRp Loop BRz Loop ; new max AND R5, R5, #0 ADD R5, R2, #0 BR Loop

Exit HALT

N1 .FILL #10 N2 .FILL #20 N3 .FILL #15 N4 .FILL #-1

.END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM