Posted on 06-19-2006, by Tim
Programs would not be valuable if they could not get data from the user. LC-3 uses an instruction called TRAP to perform its I/O functionality.
For beginners, it is not suggested to use TRAP. Instead, there are aliases that can be utilized to perform very basic input/output. These aliases will be used to show the very basics of inputting and outputting in LC-3. Later on, TRAP will be explained as well.
Use the "IN" instruction to grab a single character from the user from the console. The value that is grabbed will always be stored in the R0 register. The instruction "GETC" may also be used in place of "IN".
To nobody's surprise, the command for outputting is simply called "OUT". To simulate a working console, it is a good idea to output the character that the user just inputted.
Like inputting, data being output must also be stored in R0.
Understanding the TRAP command
IN, GETC, and OUT are all aliases of the TRAP command. Using TRAP x20 will have the same effect as using IN. Also, using TRAP x21 will perform the same action as OUT. TRAP x23 will perform both IN and OUT.
; (also outputs a prompt: "Input a character>")
Under the Hood
Inputting and outputting can be somewhat deceiving. When grabbing input from the user, you must ask yourself i"what form this data in?" Anything being input into the program will be in ASCII. In must cases, you will want to handle all numerical data in decimal. If a user enters the value "5", LC-3 will treat it as its decimal representation: 53. 53 really doesn't help us. Using that value in any calculations would distort the results because you are expecting 5.
In ASCII, numbers are conveniently placed in the same location:
Notice anything? In ASCII, the numbers are still sequential, they are just offset by a number. If all of the numbers could be subtracted by 48, then they would be equal to their decimal representations. That's exactly what we have to do in LC-3.
IN ; get input
OUT ; show the user what they entered
LD R1, ASCII_INVERSE_OFFSET ; load ascii inverse offset
ADD R0, R0, R1 ; this value is now in decimal and ready for computation
ASCII_INVERSE_OFFSET .fill #-48
Note: have a look at the full ASCII table here.
- Views: 31355