Instructions

ADD & AND

The arithmetic and logical operate instructions.

ADD Instruction

ADD is the LC-3's only arithmetic instruction. It has two modes: Register mode: ADD DR, SR1, SR2
  • Adds the values in SR1 and SR2, stores result in DR
  • Immediate mode: ADD DR, SR1, #imm5
  • Adds SR1 and a small constant (range: -16 to 15), stores in DR
  • The 5-bit immediate is sign-extended to 16 bits
  • ; Register mode
    ADD R2, R0, R1    ; R2 = R0 + R1
    
    ; Immediate mode
    ADD R3, R3, #1    ; R3 = R3 + 1 (increment)
    ADD R4, R4, #-1   ; R4 = R4 - 1 (decrement)
    
    ; Copy a register
    ADD R1, R0, #0    ; R1 = R0 + 0 = R0

    AND Instruction

    AND performs bitwise AND. Same two modes as ADD: Register mode: AND DR, SR1, SR2 Immediate mode: AND DR, SR1, #imm5
    ; Clear a register (very common pattern!)
    AND R0, R0, #0    ; R0 = R0 & 0 = 0
    
    ; Mask the lower 4 bits
    AND R1, R0, xF    ; Wait... we can't!
    ; imm5 is only 5 bits, so we'd use:
    AND R1, R0, #15   ; R1 = R0 & 0x000F

    Both ADD and AND set the condition codes (N, Z, P) based on the result written to DR. This is important for branching.

    When Do You Use ADD vs AND?

    ADD is the workhorse — you'll use it constantly:
  • Incrementing counters: ADD R1, R1, #1
  • Decrementing counters: ADD R1, R1, #-1
  • Moving pointers through arrays: ADD R1, R1, #1
  • Copying registers: ADD R1, R0, #0
  • Building up constants: ADD R0, R0, #15
  • Comparing values (by subtracting): ADD R2, R0, R1 (where R1 is negated)
  • AND has one primary use: clearing a register to zero with AND R0, R0, #0. You'll occasionally use it for bit masking, but 90% of the time, AND means "set to zero."
    Exercise

    Write a program that sets R0 = 5 and R1 = 4, then stores their sum in R2. Convert the sum to an ASCII digit (add 48) and print it with OUT.

    main.asm
    1
    R0
    x00000
    R1
    x00000
    R2
    x00000
    R3
    x00000
    R4
    x00000
    R5
    x00000
    R6
    x00000
    R7
    x00000
    PCx3000
    CC
    NZP
    Quiz

    What does `AND R3, R3, #0` do?