Reputation: 1
I am trying to read a 32-bit signed integer input, interpret it as an unsigned 32-bit value with 14 fractional bits, compute its square root, and then print the output value as a signed 32-bit value with 14 fractional bits. This is done in the RARS simulator using the RV32I instruction set of RISCV.
.data
input_raw:
.word 0
.text
.globl main
main:
# (A) Read input value
li a7, 5
ecall
la t4, input_raw # Load address of input_raw into t4
sw a0, 0(t4) # Store the input into input_raw (32,14 fixed-point format)
# Load the input_raw value
lw t5, 0(t4) # Load input_raw value into t5
# Initialize registers for binary search square root approximation
li t0, 0 # t0 = initial guess (0)
li t1, 4194304 # t1 = initial step (256 * 2^14 for fixed-point)
loop:
# (B) Square the guess and shift result
add t3, t0, t1 # t3 = t0 + t1 (current guess)
mul t6, t3, t3 # t6 = (t0 + t1)^2 (lower 32 bits)
srli t6, t6, 14 # t6 = t6 >> 14 (shift for 14 fractional bits)
# (C) Compare guess with input value
bltu t6, t5, increase_guess # If t6 < input_raw, increase guess
bgeu t6, t5, decrease_guess # If t6 >= input_raw, decrease guess
increase_guess:
# (D) Add to guess
add t0, t0, t1 # t0 = t0 + t1 (increase guess)
j halve_step # Go to halve_step
decrease_guess:
# (D) Subtract from guess
sub t0, t0, t1 # t0 = t0 - t1 (decrease guess)
halve_step:
# (E) Shift step
srli t1, t1, 1 # t1 = t1 >> 1 (halve step size)
# (F) Loop until step becomes 0
bnez t1, loop # If t1 != 0, continue looping
# (G) Print final guess
done:
mv a0, t0 # Move the final guess (output_raw) to a0
li a7, 1
ecall # Print the final square root in raw format
# Exit the program
li a7, 10
ecall
For instance, if the user inputs "409600" the output should be "81920", as 409600 represents 25 and 81920 is 5. However, the only output I get is 8388607 or -8388607. 8388607 is the maximum output value that it can be, and there should never be a negative output, as the negative should be a large positive output. I am a beginner so I am sure there is something simple I am missing, but I just cannot figure it out.
Upvotes: 0
Views: 126