11

I'm trying to write a method to do a caesar shift on a string of text in the MIPS assembly language. My encryption method is as follows:

encryptMessage:
    la $s0, message     #s0 will hold message that will be iterated through
    lw $t1, key     #s1 will hold the key to shift by
    li $t0, 0       #t0 will be iterator, starting at 0

encryptionLoop:
    add $s1, $s0, $t0   #$s1 = message[i]
    lb $s2, 0($s1)      #Loading char to shift into $s2
    beq $s2, $zero, exit    #Breaking the loop if we've reached the end: http://stackoverflow.com/questions/12739463/how-to-iterate-a-string-in-mips-assembly
    add $s2, $s2, $t1   #Shifting the character by the key amount
    la $s1, ($s2)       #Changing the character in message to the shifted character
    addi $t0, $t0, 1    #i++
    j encryptionLoop    #Going back to the beginning of the loop

However, in the exit method where I print out the supposedly encrypted message, it just prints out the message as it was originally entered. My code isn't "remembering" that I changed the characters and I can't figure out how to get it to remember. I suspect this line

la $s1, ($s2)       #Changing the character in message to the shifted character

has something to do with it but I don't know how to fix it.

Nick Gilbert
  • 4,159
  • 8
  • 43
  • 90
  • `la $s1, ($s2)` is a weird abuse of a pseudo-instruction to copy a register, and it's extra weird for human readers because `$t3` is holding a character value, not a pointer. `la` stands for "load address"; normally you'd use it like you are in `la $s0, message` to ask the assembler to emit multiple instructions that construct the address of a symbol (32-bit) in a register, e.g. using `lui` / `ori`. It's bad style to use it when the source operand is a register addressing mode, although for some reason assemblers allow that. – Peter Cordes Dec 19 '21 at 15:11

1 Answers1

8

Figured it out. That line I suspected should have been

sb $s2 ($s1)
Nick Gilbert
  • 4,159
  • 8
  • 43
  • 90
  • You missed the bug in the encryption: it doesn't wrap back into a..z range. e.g. `'z' + 1` isn't `'a'` so you need to handle that manually. ["Encrypting" a message in Assembly](https://stackoverflow.com/q/34476791) looks probably correct. – Peter Cordes Jun 22 '20 at 22:54