I have this program in the MIPS assembly that comes from C code that executes a simple middle of the arguments of an eigth function.
average8: addu $4,$4,$5 addu $4,$4,$6 addu $4,$4,$7 lw $2,16($sp) #nop addu $4,$4,$2 lw $2,20($sp) #nop addu $4,$4,$2 lw $2,24($sp) #nop addu $4,$4,$2 lw $2,28($sp) #nop addu $2,$4,$2 bgez $2,$L2 addu $2,$2,7 $L2: sra $2,$2,3 j $31
When the number is positive, we divide by 8 (shift by 3 bits), but when the number is negative, first addu 7 performs the division.
My question is: why do we add 7 to $2 when $2 is not >= 0 ?
EDIT: Here is the C code:
int average8(int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8) { return (x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8) / 8; }
Note: a possible loss in division, since we use ints instead of float or double, is not important in this case.