Search code examples
assemblyencryptionmipscaesar-cipher

Caesar cipher encrypting a single character in MIPS


I'm having some problems in creating a program to encrypt a message. At this point i'm just trying to input a char and the output should be the char+5 positions in the alphabet.

So the program should read the char in ASCII and add 5 to it and then print the letter. Ex.:

 Input: A
 Output: F

It should only work for Capital letters, so every char should be >=65 and <=90. So, if I write 'Z' it should start the alphabet from the beginning and print 'E'.

So far, my code looks like this:

    li $v0, 8               #read_string
    syscall                 #adresses char at $v0
    
    
    li $v0, 5               #char ASCII (I GUESS IT SHOULD)
    move $t0, $v0           #moves char(ASCII) to $t0
    li $s0, 90
    li $s1, 65
    bgt $t0, $s0, le_string # checks if char(ASCII) > 90
    ble $t0, $s1, le_string # checks if char(ASCII) < 65
    
        
    
    li $s0, 5               
    add $t1, $t1, $s0       #char=char+5
    move $t2, $t1           #moves encrypted char to $t2
    
    
    li $v0, 4               #print_string
    move $a0, $t2       
    syscall             

    

LOG of actual output:

25/DEZ/2015:
INPUT: A
OUTPUT: A

Solution

  • If you are using MIPS, the code should be like this:

        .text
    main:
        li $v0, 8                 # read_string
        la $a0, textbuf           # adresses of char at $a0
        li $a1, 2                 # length to read at $a1
        syscall
    
        la $t0, textbuf
        lb $v0, 0($t0)            # char ASCII (I GUESS IT SHOULD)
        move $t0, $v0             # moves char(ASCII) to $t0
        li $s0, 90
        li $s1, 65
        bgt $t0, $s0, le_string   # checks if char(ASCII) > 90
        nop                       # avoid instruction after branch begin executed even if jump is taken
        blt $t0, $s1, le_string   # checks if char(ASCII) < 65
        nop                       # avoid instruction after branch begin executed even if jump is taken
    
        li $s2, 5
        li $s3, 26
        add $t0, $t0, $s2         # char=char+5
        ble $t0, $s0, nowrap_char # checks if encrypted char <= 90
        nop                       # avoid instruction after branch begin executed even if jump is taken
        sub $t0, $t0, $s3         # wrap the char
    nowrap_char:
    le_string:
        move $t2, $t0             # moves encrypted char to $t2
    
        la $t0, textbuf
        li $v0, 4                 # print_string
        sb $t2, 0($t0)            # put the encrypted char
        la $a0, textbuf
        syscall
    
        li $v0, 10                # exit
        syscall
    
        .data
    textbuf:
        .space 2