RISC-V Instruction Encoder and Decoder (RV32I)
Type an RV32I instruction to see its machine code split into fields, or paste a hex word to decode it.
Examples: add x3, x1, x2 · lw a0, 8(sp) · sw ra, 12(sp) · beq x1, x2, -8 · jal ra, 2048 · lui x5, 0x12345
- Instruction
addi x1, x0, 5- Hex
0x00500093- Format
- I-type
000000000101imm[11:0]31:20
00000rs119:15
000funct314:12
00001rd11:7
0010011opcode6:0
| Field | Bits | Binary | Value |
|---|---|---|---|
| imm[11:0] | 31 to 20 | 000000000101 | 5 |
| rs1 | 19 to 15 | 00000 | 0 |
| funct3 | 14 to 12 | 000 | 0 |
| rd | 11 to 7 | 00001 | 1 |
| opcode | 6 to 0 | 0010011 | 19 |
The formulas
The R-type layout. Every format keeps rs1, rs2 and rd in the same bit positions, so the register file can be read before the instruction is fully decoded.
Branch offsets are in bytes and always even, so bit 0 isn't stored. Bit 31 is always the sign bit, in every format.
Worked example: addi x1, x0, 5
- addi is I-type: opcode 0010011, funct3 000.
- rd = x1 = 00001, rs1 = x0 = 00000, imm = 5 = 000000000101.
- Laid out as imm[11:0] | rs1 | funct3 | rd | opcode: 000000000101 00000 000 00001 0010011.
- That is 0x00500093, the same word GNU as produces.
- Decode 0xfe208ce3 the other way: opcode 1100011 is a branch, funct3 000 is beq, and the scattered immediate bits give −8, so it is beq x1, x2, −8.
- Branch and jump offsets are relative to the instruction's own address, in bytes.
- Pseudo-instructions such as li, mv, j and ret aren't accepted; write the base instruction (addi, jal, jalr).
- All 50 test encodings were checked against GNU as (riscv32-linux-gnu-as -march=rv32i).