MIPS: Calculating Displacement

Working through some problems and I am confused by calculating the displacement.

Some examples are:

addi    $s2, $s2, -1
addi    $s1, $s1, 1
bne $s2, $0, top

Assume top has the value of 0x1000 0008.

top:    bne     $s1, $s2, end
addi    $s1, $s1, 1        
end:    j   top

Assume top has the value of 0x1000 0008.

What is the displacement in the bne instructions?

Can anyone explain how to calculate these? Thanks.


The absolute address doesn't matter. What matters is the distance between the jump and its target.

To calculate the offset, calculate the distance between jump target and the instruction following the bne. In your first example the distance would be 12 bytes because there are 3 instructions between the target label and the instruction following the bne, and each instruction is 4 bytes in size. And since this is a backwards jump it has to be a negative offset, i.e. -12.

Since instructions need to be word aligned (4 bytes), the offset stored in the instruction word is shifted 2 bits to the right (since the two least significant bits always will be 00 anyway). This is an arithmetic shift, meaning the sign bit is preserved. So we need to take -12 and do an arithmetic right shift by 2 bits to get the actual offset that gets stored in the instruction word. This gets easier if we view -12 in hexadecimal form, which would be 0xFFF4. Shifting 0xFFF4 gives us 0xFFFD, which is what we'd put in the instruction word.

In your second example the offset will be positive, but apart from that the way you calculate it is exactly the same.

Need Your Help

Updating an existing NetworkLink

kml google-earth

I have a system set up where a simple NetworkLink is installed in many user systems.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.