Talen Kylon
Talen Kylon

Reputation: 1958

Computing offsets of a 2d array in MIPS ASM

Lets say I have a 2d array of ints with a size 36:

 game_board:   .space 36

The game board is a 6 x 6 sudoku board, broken up into 3x2 boxes:

0 0 0 | 0 0 0
0 0 0 | 0 0 0
-------------
0 0 0 | 0 0 0 
0 0 0 | 0 0 0 
-------------
0 0 0 | 0 0 0 
0 0 0 | 0 0 0  

I'm using a brute force method to solve the puzzle, and need to be able to investigate each cell and do some computation. In order to do this, I believe I need to compute the offsets for each cell location.

What I've tried so far (seen from an example) is to do the following:

 move $s0, $zero    # Begin at position 0
 li   $s1, 6        # Load $s1 with board size
 div  $s0, $s1      # Cell Offset / Board Size
 mflo $s2           # $s2 = cell row index
 mfhi $s3           # $s3 = cell column index

At this point, I'm unsure how to use $s2 and $s3 with game_board in order to get to the cell I want.

Upvotes: 0

Views: 334

Answers (1)

gusbro
gusbro

Reputation: 22585

The snippet you provided clearly won't work as you are dividing zero with 6 which clearly results in zero.

I'd suggest you write a helper routine which, given the base address of the board, row length, and desired row an column returns the address of the desired cell.

E.g.:

.data
game_board:   .space 36
.text
    la $s0, game_board
    li $s1, 6
    li $a0, 1
    li $a1, 2
    jal cell_location
    # Upon return $a3 contains address of cell

# $s0: board game base, $s1: row length (number of columns per row), $a0: row, $a1:col
# Return $a3: cell location
cell_location:
  sll $a3, $s1, 2     # row size
  multu $a3, $a0
  mflo $a3            # row base offset
  sll $a1, $a1, 2     # column offset
  addu $a3, $a3, $a1  # cell offset
  srl $a1, $a1, 2     # restore column number
  addu $a3, $s0, $a3  # cell location
  jr $ra

Upvotes: 1

Related Questions