简体   繁体   中英

incorrect loading of value from memory to register in mips

I do a project in mips in mars simulator and my program hangs on syscall due to the odd behavior.

I want to store a given char buffer to file and pass to syscall the appropriate length of it.

.data
line_length: .space 4
# ...

.text
# ...

lb  $t0, line_length
li  $v0, 15
lb  $a0, io_descriptors+4
la  $a1, output_line
move    $a2, $t0
syscall

The value stored in line_length is 0x80. And that is indeed the case also just before and after the lb instruction. The value in $t0 after lb is 0xffffff80 though, for a reason beyond my comprehension. As the number is negative, the syscall fails. What could be the reason that $t0 doesn't store 0x80 value? How can I fix it?

When loading a single byte (8 bits) into a register (32 bits on MIPS), the value needs to be extended to fill the remaining 24 bits. There are two options:

  • Zero extend which fills the remaining upper bits with zeros. This makes sense when the value is unsigned .
  • Sign extend which fills the remaining upper bits with a copy of the most-significant bit. This makes sense when the value is signed .

lb loads a single byte, and sign-extends it before putting it into the 32-bit register. Since you're reading 0x80 , the most-significant bit is a 1, so the 32-bit result is 0xFFFFFF80 .

Since you've declared line_length to be 4 bytes, you want to use lw which loads a full 32-bit word (with no extension). Just make sure you're being consistent with the instructions you use to access and manipulate this variable.

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM