This program I created in RISC-V RARS 1.3 application is designed to take a decimal number and count how many bits are in that number. The one I am testing is the decimal number 5, and this program should work for any positive number I put on t1. Here is the code I created. The program is meant to add one counter whenever the result of the AND function is not 0, but the problem I have is that the program does not stop. Is there a solution to this problem?
_start:
li t1,2 # start with decimal 5, binary 101
li t2,1 # adding counter for AND function
li t3,0 # bit counter count
li t4,0 # to compare 0
and t5,t1,t2 # t1 & t2 = t5
bne t5,t4,label # go to label if t5 != 0
beqz t5,label2 # go to label if t5 == 0
label:
addi t3,t3,1 # add one to bit count
slli t2,t2,1 # shift left
and t5,t1,t2 # t1 & new t2 = t5
bne t5,t4,label # go to label if t5 != 0
beqz t5,label2 # go to label if t5 == 0
label2:
slli t2,t2,1 # shift left
and t5,t1,t2 # t1 & new t2 = t5
.data
Since you start with
t2 = 1and multiply it by2in each iteration, you should stop the calculation once the value oft2becomes greater thant1.Also, in your code, I see you that you probably intended to handle two cases:
label:- this block handles the case when the current bit tested is 1, it increments the number of bits and then jumps to eitherlabelorlabel2. Here, you just need to add the exit condition as mentioned abovelabel2:- this block handles the case when the current bit tested is 0, it does not change the number of bits, but it also does not seem to continue with eitherlabelorlabel2. I think that is should keep looking whether there are any higher 1 bits, until the exit conditiont2>t1is reached.