I am writing this code for a problem where I have to read integers from file and store them into an array to perform other operations. So far I have been able to read from file and store them into the buffer.
#### Read Data from File
li $v0, 14 # system call for read from file
move $a0, $s6
la $a1, buffer # address of buffer from which to read
li $a2, 1000 # hardcoded buffer length
syscall # read from file
When I do this: it sucessfuly displays the content of the file which are integers on separate lines.
li $v0, 4 # syscall for printing a string
la $a0, buffer # load read data in $a0
syscall
I am stuck at this point where I have to store these integers in the buffer into an array. How is this done?
You didn't give us a lot of information to go on so I will be assuming your file looks something like this:
1234 523 54326 7131
(It can be line-delimited, the concept is the same)
Once you read the number into a string, you have to parse it into an integer. And then store it in an integer array. Your array should look something like this:
.align 2 # word-aligned
array: .space 40 # a word array of 10 elements
To parse the string to an integer you can barrow the concept from C, which has atoi() which looks something like this:
#
# int atoi ( const char *str );
#
# Parse the cstring str into an integral value
#
atoi:
or $v0, $zero, $zero # num = 0
or $t1, $zero, $zero # isNegative = false
lb $t0, 0($a0)
bne $t0, '+', .isp # consume a positive symbol
addi $a0, $a0, 1
.isp:
lb $t0, 0($a0)
bne $t0, '-', .num
addi $t1, $zero, 1 # isNegative = true
addi $a0, $a0, 1
.num:
lb $t0, 0($a0)
slti $t2, $t0, 58 # *str <= '9'
slti $t3, $t0, '0' # *str < '0'
beq $t2, $zero, .done
bne $t3, $zero, .done
sll $t2, $v0, 1
sll $v0, $v0, 3
add $v0, $v0, $t2 # num *= 10, using: num = (num << 3) + (num << 1)
addi $t0, $t0, -48
add $v0, $v0, $t0 # num += (*str - '0')
addi $a0, $a0, 1 # ++num
j .num
.done:
beq $t1, $zero, .out # if (isNegative) num = -num
sub $v0, $zero, $v0
.out:
jr $ra # return
(Just like the C atoi() function, it's got no error-checking mechanism, you might want to add that).
Parse each individual number from the file (by passing it to atoi()) and store it in the array as an integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With