Getting User Input
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.


Basic Input

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".


Basic Output

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.

Code:
IN
OUT


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.

TRAP commandsAliases
x20GETC
x21OUT
x22PUTS
x23GETC
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:

ASCIIDecimal
048
149
250
351
452
553
654
755
856
957


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.

Code:
.ORIG x3000
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

HALT

ASCII_INVERSE_OFFSET .fill #-48

END


Note: have a look at the full ASCII table here.
Difficulty: Intermediate - Views: 25195

User Comments
chaoscreater wrote:
well written and explained, however i think Trap X23 is IN, not GETC and OUT......While it does do the same function as GETC, i'm pretty sure it doesn't OUT the input, it just prompts the user to enter something and stores it.


Copyright 2006 © LC3Help.com v1.4.7