Subtraction
Subtraction in RISC-V assembly is done using one of two instructions:
subfor subtracting the values of two registersaddiwith a negative immediate value for subtracting an immediate value from a register
Subtracting using registers
Section titled “Subtracting using registers”Suppose we have two registers, x1 and x2, which contain the values 10 and
3 respectively, and we want to subtract the value in x2 from the value in
x1, and store the result in x3.
In other words:
x1 = 10x2 = 3x3 = x1 - x2We can do that using the sub instruction like this:
sub x3, x1, x2Or, the full code:
.textmain: li x1, 10 li x2, 3 sub x3, x1, x2
stop: li a7, 10 ecallOnce we run this code, the value in register x3 will be 7, or 07 in hex!
Subtracting an immediate value
Section titled “Subtracting an immediate value”Suppose we have a register, x1, which contains the value 10, and we want to
subtract 3 from it and store the result in x2.
In other words:
x1 = 10x2 = x1 - 3But we can also subtract the number 3 by adding -3 to x1!
In Python, that would look like this:
x1 = 10x2 = x1 + (-3) # (brackets optional)We can do that in RISC-V assembly using the addi instruction with a negative
immediate value:
addi x2, x1, -3The full code being:
.textmain: li x1, 10 addi x2, x1, -3
stop: li a7, 10 ecallAs this code effectively does the same as the previous example, the value in
register x2 will also be 7 when running the code!