Reputation: 809
A user enters a binary number(ie: 110100), I need to calculate the number of consecutive 0's starting from the LSB, so it would be 2 in the case of 110100.
My problem is counting the length of this entered string. But I found this to be impossible because im checking by way of
beqz $t2,finished
which will immeadiately stop at the first 0 at 110, even though we know this is not the end of the string.
My attempt:
## Read string from user ##
la $a0, str
li $a1, 100
li $v0, 8
syscall
##
## Loop each byte in string until null-terminator is found ##
loop:
move $t0,$t1
add $t0,$t0,$a0 # current address($t0)=counter*1(size of character in bytes)+RAM address of start of array
lb $t2,($t0) # load next byte in string
lw $s0, del
beqz $t2,finished # if current character==null-terminator, exit loop
addi $t1,$t1,1 # increase counter
beqz $t2,addtoh
j loop # loop around
addtoh:
addi $t3,$t3,1 #
j loop # loop around
finished:
##
#################################################
# #
# data segment #
# #
#################################################
.data
str: .space 100
endl: .asciiz "\n"
Upvotes: 1
Views: 3203
Reputation: 1076
I don't see where you're initializing $t1
. Unlike high-level languages, machine code doesn't initialize memory or registers automatically. $t1
could be starting out anywhere. So when you do this:
move $t0,$t1 # unknown 32-bit value loaded into $t0
add $t0,$t0,$a0 # $t0 is now an unknown number of bytes past (or before!) the start of the buffer
lb $t2,($t0) # load next (random) byte in string
... you could end up looking at bytes anywhere in the memory space. And since a lot of those bytes will end up being zero, your code will finish sooner than you expected.
Upvotes: 1