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
Fields of addi x1, x0, 5
FieldBitsBinaryValue
imm[11:0]31 to 200000000001015
rs119 to 15000000
funct314 to 120000
rd11 to 7000011
opcode6 to 0001001119

The formulas

funct7⏟31:25rs2⏟24:20rs1⏟19:15funct3⏟14:12rd⏟11:7opcode⏟6:0\underbrace{\text{funct7}}_{31:25}\quad \underbrace{\text{rs2}}_{24:20}\quad \underbrace{\text{rs1}}_{19:15}\quad \underbrace{\text{funct3}}_{14:12}\quad \underbrace{\text{rd}}_{11:7}\quad \underbrace{\text{opcode}}_{6:0}

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.

immB={ inst[31], inst[7], inst[30:25], inst[11:8], 0 }\text{imm}_B = \{\,\text{inst}[31],\ \text{inst}[7],\ \text{inst}[30{:}25],\ \text{inst}[11{:}8],\ 0\,\}

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

  1. addi is I-type: opcode 0010011, funct3 000.
  2. rd = x1 = 00001, rs1 = x0 = 00000, imm = 5 = 000000000101.
  3. Laid out as imm[11:0] | rs1 | funct3 | rd | opcode: 000000000101 00000 000 00001 0010011.
  4. That is 0x00500093, the same word GNU as produces.
  5. 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).

Sources