mipscpu-architecturemips32sign-extension

load byte instruction in MIPS


I am learning about Computer architecture through the MIPS instructions. I have a question which is:

Memory at 0x10000000 contains 0x80 Register $5 contains 0x10000000 What is put in register $8 after lb $8,0($5) is executed?

I was thinking when the load byte is called, it will take the 8 bits of 0x80[10000000] from the 0x10000000 address and load it into the first 8 bits of the $8 register and fill the remaining bits with zeros making the answer to be 00000080. But the correct answer listed is FFFFFF80. I am not sure if I understand it. Can anybody help explain it?


Solution

  • The instruction you mention here is lb which loads a one byte into a register by sign-extending the byte to the word size. This means if the most significant bit is set to 1 it will fill the remaining 24 bits with 1 as well. This is done to preserve the twos-complement value of the byte in a 32 bit representation.

    If your byte would be 0100 1010 the sign-extend would fill it with 0 as 0000 000... 0100 1010.

    If your byte would be 1011 0101 the sign-extend would fill it with 1 as 1111 111... 1011 0101.

    To avoid this and always pad the byte with 0 you can use the alternative lbu instruction which does not perform a sign-extend but pads the byte with 0 instead. This preserves the unsigned value of the byte since twos-complement is not involved for those.