hi all,
i got a program that calculates the fibonacci numbers and prints them out, looks something like this:

main:
li $s0, 0
li $s1, 1
loop:
slt $t0, $s1, $s0
bgtz $t0, done
addu $s2, $s0, $s1
move $s0, $s1
move $s1, $s2
li $v0, 1
move $a0, $s2
syscall
j loop
done:
jr $ra

so ok when i execute it it gives me a list of fibonacci numbers. i would have expected a infinite loop however the last number it gave me was 1836131903

and then the next thing it gave me was -1323752223

can any1 explain this?

it cant be because it reached the maximum value a register can store right? because a register has 32 bits therefore stores up to 4billion, however if the program kept going the next number should have been 1836131903 + 1134903170 = 2971035037 which is < 4 billion so it should have been ok?

pls help! XD

EDIT: o i just found that the last two fibonnaci numbers added together gives:

1836131903 + 1134903170 = 2971035037

and the max number a 32 bit register can store is 2^32
and if compute:

2971035037 - 2^32 = -1323752223

the maths is all there pls someone explain to me!

By performing this calculation:
1836131903 + 1134903170 = 2971035037,
you've set the top bit of a 32 bit register. That's still within the 32 bit range of the register but the "bgtz $t0, done" instruction is checking whether the register is greater than zero. The top bit is the sign bit and indicates that the number held in the register is negative, so the program terminates. Your output is also treating the register as signed and taking the sign bit into account. If you could display it as a 32 bit unsigned number you would see the correct value.

Hi I dont think this should be happening because in the assembly code the command was:

addu $s2, $s1, $s0

addu is the command for adding unsigned numbers isnt it?

Hi I dont think this should be happening because in the assembly code the command was:

addu $s2, $s1, $s0

addu is the command for adding unsigned numbers isnt it?

Yes, that addu is unsigned and works fine, but when the bgtz looks at the register it sees those same bits in a different way and thinks it's negative.

This article has been dead for over six months. Start a new discussion instead.