0

Suppose we needed to jump to the memory address 0xAE87698C. If the current PC value is 0xAF70018B show the j instruction to perform the jump (display it as both a 32-bit binary number and as an equivalent hex value)

I know I need to shift one of them left, and then use the four upper bits from the PC for the new address, but I'm getting confused on when/which to shift, and when to add the PC value

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
eswcs
  • 5
  • 3
  • Basically a duplicate of [How to Calculate Jump Target Address and Branch Target Address?](https://stackoverflow.com/q/6950230) which includes a worked example for a `jal` instruction (which encodes a target the same way `j` does). – Peter Cordes Feb 22 '23 at 03:20

1 Answers1

1

It's easy if you remember that instructions are 4 bytes and always aligned. As such the two low bits will always be zero and there is no reason to store them. That's why you shift by 2, to chop them off. If you then look at the instruction encoding, you realize the top 6 bits are the opcode and the address only has 26 bits available. Since we already chopped two bits off, our address is 30 bits so the top 4 bits will not fit. During encoding, you should verify that these bits are the same as the current PC. During decoding, those bits will be filled from the PC.

In your example, you have 0xAE87698C. The top 4 bits is just the leading hex digit so that's easy to compare with the PC. It checks out, both have 0xA there. We can then work with the rest of the bits: 0x0E87698C. Shift that by 2 bits (divide by 4) and that will give the low 26 bits of the instruction: 0x3A1DA63. The top 6 are the opcode which has fixed value 000010b or when shifted into place 0x08000000. You can combine the two parts by adding or using bitwise OR to get the encoding 0x0BA1DA63. You can also work in binary if that's easier for you, but it's more tedious and error prone.

Jester
  • 56,577
  • 4
  • 81
  • 125