Friday, March 6, 2020

MIPS code: xor operation is reversible

This is a sample MIPS assembler code used to prove that xor operation is reversible. In other words, xor-ing Number A with any Number B and xor-ing the result with Number B again results in Number A.

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.


# --------------- XOR operation is reversible ------------------ #

# For example:
# Number A = 0x01234567
# Number B = 0x0000ffff

# Expected output:
# Number to XOR: 0x01234567
# After 1st XOR: 0x0123ba98
# After 2nd XOR: 0x01234567
# XOR is reversible!

# -------------------------------------------------------------- #
.text

main:
    # li pseudo-instruction accepts 32-bit numbers
    li $s0, 0x01234567

# .............................................................. #

    # Print "Number to XOR: "
    la $a0, szNumber
    li $v0, 4
    syscall

# .............................................................. #

    # Let's print integer number to XOR
    move $a0, $s0
    li $v0, 34
    syscall

# .............................................................. #

    # Print "After 1st XOR: "
    la $a0, szOutput1
    li $v0, 4
    syscall

# .............................................................. #
    
    # xori expects 16-bit immediate
    xori $t0, $s0, -1     # -1 = 0xffff
    # the result in $t0 should be 0x0123ba98

# .............................................................. #
    
    # print the integer result of the xori above
    move $a0, $t0
    li $v0, 34            # print in Hex!
    syscall

# .............................................................. #
    
    # Print "\nAfter 2nd XOR: "
    la $a0, szOutput2
    li $v0, 4
    syscall

# .............................................................. #

    xori $t0, $t0, 0xffff
    # the result in $s0 will be 0x01234567

    # Let's print it!
    move $a0, $t0
    li $v0, 34
    syscall

    bne $s0, $t0, exit
    # Print "\nXOR is reversible!\n"
    la $a0, szReversibe
    li $v0, 4
    syscall

exit:
    li $v0, 10            # Exit program
    syscall

# -------------------------------------------------------------- #

.data
szNumber:    .asciiz "Number to XOR: "
szOutput1:   .asciiz "\nAfter 1st XOR: "
szOutput2:   .asciiz "\nAfter 2nd XOR: "
szReversibe: .asciiz "\nXOR is reversible!\n"

# -------------------------------------------------------------- #


Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment