You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LC-3技术问询:如何将字符串存入非R0寄存器并正常打印?

Fixing LC-3 String Printing with R3 (or Any Register)

Great question! Let's break down why your code isn't working and fix it right away.

The Root Cause: LC-3 Trap Instruction Rules

The TRAP x22 (PUTS) trap in LC-3 has a strict requirement: it always reads the starting address of the string to print from register R0. Your original code loads the string address into R3, but PUTS doesn't look at R3 at all—it checks R0, which contains random garbage values when your program starts. That's why you only see the halting message instead of your string.

Fixed Code

Here's how to adjust your code to keep the string address in R3 and still print correctly:

.ORIG x3000
LEA R3, L1       ; Load string address into R3 (this part is totally fine!)
ADD R0, R3, #0   ; Critical step: Copy R3's value into R0 (PUTS needs R0)
L1 .STRINGZ "Hello World"
TRAP x22         ; Now PUTS reads the correct address from R0 and prints
TRAP x25
.END

Bonus: Preserving R0's Original Value

If you need to keep whatever was originally in R0 (for other parts of your program), you can save it to memory first, then restore it after printing:

.ORIG x3000
ST R0, SAVE_R0   ; Save R0's initial value to a memory location
LEA R3, L1
ADD R0, R3, #0
L1 .STRINGZ "Hello World"
TRAP x22
LD R0, SAVE_R0   ; Restore R0 to its original value
TRAP x25
SAVE_R0 .BLKW 1  ; Reserve 1 word of memory to hold R0's saved value
.END

Key Takeaway

All LC-3 trap instructions have fixed register conventions:

  • PUTS (x22): Uses R0 for the string address
  • OUT (x21): Uses R0 for the character to print
  • GETC (x20): Stores input character in R0
  • PUTSP (x23): Uses R0 for the string address (for printing with spaces)

Always follow these conventions, and your traps will work as expected!

内容的提问来源于stack exchange,提问作者Hexedecimal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:32:05