; File: WriteInt.asm ; Written By: Deepak Kumar ; Date: April 9, 2024 ; Purpose: ; Test the WriteInt subroutine .ORIG x3000 TEST LD R0, integer JSR WriteInt HALT integer .FILL #243 ; The number to be output ; ; WriteInt: ; Given a number in R0, print it out. For now, only positive numbers (>0) allowed. ; ; Algorithm ; n <- # to output ; s[6] is the output string (null terminated) ; s[5] <- '\0' ; i <- 4 ; while N > 0 do ; n <- n/10 ; r <= r % 10 ; s[i] <- r + 48 ; i <- i - 1 ; output s to display ; Registers: ; R0: n ; R2: n ; R1: r ; R4: @s ; R3: 10 ; R5: 48 (ASCII for '0') ; WriteInt ST R0, PNR0 ST R1, PNR1 ; Save registers being used ST R2, PNR2 ST R3, PNR3 ST R4, PNR4 ST R5, PNR5 ST R7, PNR7 ; Create the empty string LEA R4, OutStr ; set up ouput string (s) ADD R4, R4, #5 AND R2, R2, #0 STR R2, R4, #0 ; Store null in last location of string ADD R4, R4, #-1 ; Ready for next char ; set up dividend, and ASCII for '0' (48) AND R3, R3, #0 ADD R3, R3, #10 ; the dividend LD R5, ASCII ; while R2 > 0 : Check flags for value in R2 REPEAT ADD R2, R0, #0 ; R2 = R0 move for DIVMOD BRnz PrDone ; do JSR DIVMOD ; Convert remainder in R1 to ascii and store ; R1 needs to be converted to ascii and added to string ADD R1, R1, R5 ; add 48 to R1 STR R1, R4, #0 ; Strore char (digit) in OutStr ADD R4, R4, #-1 ; location of next char/digit ADD R2, R0, #0 ; Move quotient to R2 for next round BR REPEAT PrDone ADD R0, R4, #1 ; R0 <- addr of OutStr PUTS ; Outputs the constructed string LD R0, PNR0 ; restore all saved registers LD R1, PNR1 LD R2, PNR2 LD R3, PNR3 LD R4, PNR4 LD R5, PNR5 LD R7, PNR7 RET ASCII .FILL x30 ; code for '0' is x30 or #48 Outstr .BLKW 6 ; string that will be constructed PNR0 .BLKW 1 PNR1 .BLKW 1 PNR2 .BLKW 1 PNR3 .BLKW 1 PNR4 .BLKW 1 PNR5 .BLKW 1 PNR7 .BLKW 1 ; ; DIVMOD ; q <- A/B ; remainder <- A % B ; Algorithm ; A = 22 ; B = 7 ; quotient = 0 ; while A >= B do ; A = A - B ; q = q + 1 ; remainder = A ; ; Registers: ; R2 contains dividend (A), R3 contains divisor (B) ; Result is put in R0 (Quotient) and R1 (remainder) ; R4 is used to store -R3 ; R5 is used to store the result of subtraction (A - B) ; Registers: R0 and R1 will return results. ; DIVMOD ST R3, Sr3 ; Save registers being used ST R4, Sr4 ST R5, Sr5 ADD R1, R2, #0 ; R1 = R2 (A) NOT R4, R3 ; R4 = -R3: R4 = NOT(R3) and Adding 1 to R4 ADD R4, R4, #1 AND R0, R0, #0 ; R0 = 0 ; while R1 >= R3 : R5 = R1 - R3 : R5 = R1 + R4 LOOP ADD R5, R1, R4 BRn DONE ; do ADD R1, R1, R4 ; R1 = R1 - R3 ADD R0, R0, #1 ; R0 = R0 + 1 BR LOOP DONE LD R3, Sr3 ; restore registers LD R4, Sr4 LD R5, Sr5 RET Sr3 .BLKW 1 Sr4 .BLKW 1 Sr5 .BLKW 1 .END