2

I am new to LC-3 assembly language and writing a program that compares two characters. The program prompts the user to enter in a character to check for (I used GETC to load the user input into R0).

The skeleton code I was given loads the negated value of 'g' into R0, which is given as xFF99 in hex (I'm not sure how this value was obtained, though, as it was given). Then, a separate character is loaded into R7 and to check if they are equal, the program adds R0 to R7 and the result is stored in R0. Then, a branch statement runs if the zero condition code is set.

My question is how do I get the negated value of what a user inputs? All I must do is simply used GETC to get the user input into R0, and then negate that value. After that, the program will work as intended.

Slippy
  • 93
  • 1
  • 10
  • 2
    A different assembly language exists for every processor architecture. Please tag your question with the appropriate architecture tag. – Jonathon Reinhart Dec 05 '20 at 22:17
  • Sorry! I will do that now. I am using LC-3's ISA – Slippy Dec 05 '20 at 22:19
  • 2
    LC-3, like very other computer these days, uses [two's complement](https://en.wikipedia.org/wiki/Two's_complement) arithmetic. To negate a number, flip all the bits (think `NOT`) and add 1. If the value of interest is a build-time constant, it is generally easier to perform the negation in your head and write that number into your source code instead doing the negation at runtime. Here, for example, 0xFF99 = -103. Instead of subtracting 103 or taking 103 and negating it, we can add -103. – Erik Eidt Dec 05 '20 at 22:20
  • @ErikEidt Thank you! Forgot to add the one after running NOT – Slippy Dec 05 '20 at 22:28

1 Answers1

3

LC-3 does not have a negation instruction, nor even a subtraction instruction (!), so instead you need to negate numbers by constructing the 2’s complement directly. This entails complementing the bits with the NOT instruction, and then incrementing by 1 with ADD.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • How did this get downvoted? It's correct, [LC-3 is lacking a subtract instruction](https://www.cs.utexas.edu/users/fussell/courses/cs310h/lectures/Lecture_10-310h.pdf) so you have to use a 2's complement identity to implement `-x`. [How to prove that the C statement -x, ~x+1, and ~(x-1) yield the same results?](https://stackoverflow.com/q/2278518) / [Explain why x == ~(~x + 1) + 1 (two's complement and back!)](https://stackoverflow.com/q/33566989). Otherwise on most ISAs you'd just subtract from 0. – Peter Cordes Dec 05 '20 at 22:39