vc2910
vc2910

Reputation: 1

Unable to convert RISC-V to Machine code -- difficulty with handling immediate value

I need to convert each of the following RISC-V instructions to machine code.

Format answer as 32-bit hexadecimal number, e.g. 0xABADCAFE or 0xabadcafe (the cafe just sucks). Leave any unused bits as 0.

Refer to this sheet if needed.

Q1. jal ra, fib

Assume PC=0x00400014, and fib is located at 0x00400028.

Q2. beq t3, t5, NEXT

Assume PC=0x0040011C, and NEXT is located at 0x0040010C.

Upvotes: 0

Views: 3265

Answers (1)

Justus Polzin
Justus Polzin

Reputation: 21

The immediate of the jal instruction is relative to the program counter (pc). So the immediate encoded in the instruction is 0x00400028 - 0x00400014 = 0x14 = 0b10100. Looking at the cheat sheet, we can see in what order the bits are encoded in the instruction: [20|10:1|11|19:12] (bit 0 is not encoded since all instructions are encoded in an even number of bytes). Plugging everything in we can see that the immediate is encoded as 0|0000001010|0|00000000. Adding in the register ra (x1) and the opcode (1101111) leads to the binary number 0|0000001010|0|00000000|00001|1101111, which is 0x014000EF in hexadecimal.

The approach is the same for the beq instruction. The difference here is that the instruction jumped to comes before the branch instruction (immediate = 0x0040010C - 0x0040011C = -0x10). Risc-V interprets the immediate as a signed number in two's complement. Because the immediate is 12 bits in size it's encoding would be: -0x10 = 0b1111'1111'0000. Adding it all together leads to: 1|111111|11110|11100|000|1000|1|1100011 = 0xFFEE08E3.

Upvotes: 2

Related Questions