---
title: Instruction encoding lab
heading: Encoding and decoding RISC-V instructions in Python
eyebrow: C8 · Lesson 7 · Instruction encoding lab
xp: 50
---

::: hook
An assembler turns `beq t0, t1, loop` into 32 bits, and a processor's decoder, an emulator or a debugger turns those bits back into fields. All of them are a few shifts and masks. In this lab you'll write the pieces in Python: sign extension, I-type and B-type encoders, a field decoder and a small disassembler, each checked against the words this course's own assembler produces.
:::

::: play
- The memory window shows the program as it sits in memory: one 32-bit word per instruction, starting at address 0.
- Step through. Each word is an instruction from lesson 4's formats: an I-type `addi`, an R-type `sub`, an S-type `sw`, an I-type `lw`, and two B-type branches: one forward 8 bytes to leave the loop, one back 8 bytes to repeat it until t2 reaches 10.
- Pick a word and split it by hand: the low 7 bits are the opcode, and the rest falls into the fields of its format.
:::

```sim cpu
    addi t0, zero, 10     # 0x00A00293
    sub a0, a1, a2        # 0x40C58533
    addi sp, sp, -16      # 0xFF010113
    sw a0, 8(sp)          # 0x00A12423
    lw t1, 8(sp)          # 0x00812303
x:  addi t2, t2, 1       # 0x00138393
    beq t2, t0, done      # 0x00538463: ahead 8 bytes
    beq t1, t1, x         # 0xFE630CE3: back 8 bytes
done:
    ebreak
show: t0, t1, t2, a0
hex: sp
memory: 0x0000..0x0024
speed: 4
```

::: predict
## A B-type instruction can branch ±4 KiB in steps of 2 bytes. How many immediate bits does the instruction actually store?

- [ ] 13
- [x] 12
- [ ] 11
- [ ] 20

::: reveal
12. The offset is a 13-bit signed number (bits 12 to 0), but bit 0 is always 0, because instructions sit on 2-byte boundaries, so only bits 12 to 1 are stored. They're scattered across bits 31, 30 to 25, 11 to 8 and 7 of the word, so that the register fields stay in the same places as in the other formats.
:::
:::

::: nameit
## Fields with shifts and masks

To read a field of w bits starting at bit p: `(word >> p) & ((1 << w) - 1)`. To place one: `(value & mask) << p`, combined with `|`.

| Format | 31:25 | 24:20 | 19:15 | 14:12 | 11:7 | 6:0 |
|---|---|---|---|---|---|---|
| R | funct7 | rs2 | rs1 | funct3 | rd | opcode |
| I | imm[11:5] | imm[4:0] | rs1 | funct3 | rd | opcode |
| S | imm[11:5] | rs2 | rs1 | funct3 | imm[4:0] | opcode |
| B | imm[12], imm[10:5] | rs2 | rs1 | funct3 | imm[4:1], imm[11] | opcode |

## Sign extension

A field of b bits holding a two's-complement number is negative when its top bit is set, and then its value is the unsigned value minus $2^b$:

$$x = u - 2^b \cdot [u \ge 2^{b-1}]$$

Python's integers never overflow, so masking a negative number with `& 0xFFF` gives exactly its 12-bit two's-complement pattern.
:::

::: example
## Encode `sw a0, 8(sp)` by hand.

::: solution
1. **Split the immediate.** S-type splits 8 into imm[11:5] = 0 and imm[4:0] = 8.
2. **The other fields.** rs2 = a0 = 10, rs1 = sp = 2, funct3 = 010 for a word, opcode 0x23.
3. **Assemble the word.**
   $$\begin{aligned} &10 \cdot 2^{20} + 2 \cdot 2^{15} \\ &+ 2 \cdot 2^{12} + 8 \cdot 2^7 \\ &+ \text{0x23} \\ &= \text{0x00A12423} \end{aligned}$$
4. **Check.** That's the word the assembler gave in the program above.

**Answer:** `sw a0, 8(sp)` is 0x00A12423.
:::
:::

::: example
## Decode 0xFE628EE3.

::: solution
1. **Opcode and funct3.** Opcode 0x63 is a branch, and funct3 = 000 makes it `beq`.
2. **Registers.** rs1 = bits 19:15 = 5 (t0), and rs2 = bits 24:20 = 6 (t1).
3. **Gather the immediate's bits.** Bit 31 = 1 gives imm[12], bits 30:25 = 111111 give imm[10:5], bits 11:8 = 1110 give imm[4:1], and bit 7 = 1 gives imm[11].
4. **Put them in order.** Together, 1 1111111 1110 0 = 0x1FFC.
5. **Sign-extend from 13 bits.**
   $$\text{0x1FFC} - \text{0x2000} = -4$$

**Answer:** `beq t0, t1, -4`, a branch to the previous instruction.
:::
:::

::: check
given: u = 2048..4095 int
answer: u - 4096
tolerance: 0

## What's {u} (a 12-bit field) sign-extended?

::: right
Right: {answer}.
:::

::: misses
- [u] Its top bit is set, so it's negative.
- [any] Not yet. Subtract $2^{12}$.
:::
:::

::: check
kind: python

## Write `sign_extend(value, bits)`: the low `bits` bits of `value` read as a two's-complement number.

```python starter
def sign_extend(value, bits):
    return value
```

```python solution
def sign_extend(value, bits):
    value &= (1 << bits) - 1
    if value & (1 << (bits - 1)):
        value -= 1 << bits
    return value
```

```python tests
assert sign_extend(0xFFF, 12) == -1, f"0xFFF in 12 bits is -1, got {sign_extend(0xFFF, 12)}."
assert sign_extend(0x7FF, 12) == 2047, "0x7FF in 12 bits is 2047: its top bit is clear."
assert sign_extend(0x800, 12) == -2048, f"0x800 in 12 bits is -2048, got {sign_extend(0x800, 12)}."
assert sign_extend(0x1F, 5) == -1, "0x1F in 5 bits is -1."
assert sign_extend(0x10, 6) == 16, "0x10 in 6 bits is 16."
assert sign_extend(0xFFFFF800, 12) == -2048, "Only the low 12 bits count: 0xFFFFF800 gives -2048."
```

::: right
Right. Mask to the field, then subtract $2^b$ if the top bit is set.
:::
:::

::: check
kind: python

## Write `encode_i(imm, rs1, funct3, rd, opcode)`: the 32-bit I-type word. `imm` may be negative (−2048 to 2047).

```python starter
def encode_i(imm, rs1, funct3, rd, opcode):
    return (imm << 20) | (rs1 << 15) | (funct3 << 12) | (rd << 7) | opcode
```

```python solution
def encode_i(imm, rs1, funct3, rd, opcode):
    return ((imm & 0xFFF) << 20) | (rs1 << 15) | (funct3 << 12) | (rd << 7) | opcode
```

```python tests
assert encode_i(10, 0, 0, 5, 0x13) == 0x00A00293, f"addi t0, zero, 10 is 0x00A00293, got {encode_i(10, 0, 0, 5, 0x13):#010x}."
assert encode_i(8, 2, 2, 10, 0x03) == 0x00812503, "lw a0, 8(sp) is 0x00812503."
assert encode_i(-1024, 5, 0, 5, 0x13) == 0xC0028293, f"addi t0, t0, -1024 is 0xC0028293, got {encode_i(-1024, 5, 0, 5, 0x13):#x}. Mask a negative immediate to 12 bits."
assert encode_i(-4, 2, 2, 6, 0x03) == 0xFFC12303, "lw t1, -4(sp) is 0xFFC12303."
```

::: right
Right. Python's `& 0xFFF` turns −1024 into its 12-bit pattern, 0xC00.
:::
:::

::: check
kind: python

## Write `decode(word)`: a dict with the fields `opcode`, `rd`, `funct3`, `rs1`, `rs2`, `funct7`, and `imm_i` (bits 31:20 sign-extended).

```python starter
def decode(word):
    return {'opcode': word, 'rd': 0, 'funct3': 0, 'rs1': 0, 'rs2': 0, 'funct7': 0, 'imm_i': 0}
```

```python solution
def decode(word):
    imm = (word >> 20) & 0xFFF
    if imm & 0x800:
        imm -= 0x1000
    return {
        'opcode': word & 0x7F,
        'rd': (word >> 7) & 0x1F,
        'funct3': (word >> 12) & 0x7,
        'rs1': (word >> 15) & 0x1F,
        'rs2': (word >> 20) & 0x1F,
        'funct7': (word >> 25) & 0x7F,
        'imm_i': imm,
    }
```

```python tests
d = decode(0x00812503)
assert (d['opcode'], d['rd'], d['funct3'], d['rs1'], d['imm_i']) == (3, 10, 2, 2, 8), f"0x00812503 is lw a0, 8(sp): opcode 3, rd 10, funct3 2, rs1 2, imm 8; got {d}."
d = decode(0x40C58533)
assert (d['opcode'], d['rd'], d['rs1'], d['rs2'], d['funct7']) == (0x33, 10, 11, 12, 0x20), f"0x40C58533 is sub a0, a1, a2; got {d}."
assert decode(0xFFC12303)['imm_i'] == -4, "0xFFC12303 has the immediate -4."
assert decode(0xC0028293)['imm_i'] == -1024, "0xC0028293 has the immediate -1024."
```

::: right
Right. A hardware decoder does the same: it's just wires, with sign extension copying bit 31.
:::
:::

::: check
kind: python

## Write `encode_b(offset, rs2, rs1, funct3)`: a branch word (opcode 0x63) for an even byte offset from −4096 to 4094.

```python starter
def encode_b(offset, rs2, rs1, funct3):
    return ((offset & 0xFFF) << 20) | (rs2 << 20) | (rs1 << 15) | (funct3 << 12) | 0x63
```

```python solution
def encode_b(offset, rs2, rs1, funct3):
    imm = offset & 0x1FFF
    return (((imm >> 12) & 1) << 31) | (((imm >> 5) & 0x3F) << 25) | (rs2 << 20) | (rs1 << 15) \
        | (funct3 << 12) | (((imm >> 1) & 0xF) << 8) | (((imm >> 11) & 1) << 7) | 0x63
```

```python tests
assert encode_b(16, 6, 5, 0) == 0x00628863, f"beq t0, t1, +16 is 0x00628863, got {encode_b(16, 6, 5, 0):#010x}."
assert encode_b(-4, 6, 5, 0) == 0xFE628EE3, f"beq t0, t1, -4 is 0xFE628EE3, got {encode_b(-4, 6, 5, 0):#x}."
assert encode_b(4, 9, 8, 4) == 0x00944263, "blt s0, s1, +4 is 0x00944263."
assert encode_b(100, 11, 10, 5) == 0x06B55263, "bge a0, a1, +100 is 0x06B55263."
assert encode_b(-2048, 11, 10, 1) == 0x80B510E3, "bne a0, a1, -2048 is 0x80B510E3: imm[11] lands in bit 7."
```

::: right
Right. Four pieces of the offset, each shifted to its own place.
:::
:::

::: check
kind: python

## Write `disassemble(word)` for `add`, `sub`, `addi`, `lw`, `sw` and `beq`, returning text like `add x10, x11, x12`, `addi x5, x0, 10`, `lw x10, 8(x2)`, `sw x10, 8(x2)` or `beq x5, x6, -4`. Anything else gives `unknown`. `sign_extend` is provided.

```python starter
def sign_extend(value, bits):
    value &= (1 << bits) - 1
    return value - (1 << bits) if value & (1 << (bits - 1)) else value

def disassemble(word):
    return 'unknown'
```

```python solution
def sign_extend(value, bits):
    value &= (1 << bits) - 1
    return value - (1 << bits) if value & (1 << (bits - 1)) else value

def disassemble(word):
    op = word & 0x7F
    rd, f3, rs1, rs2, f7 = (word >> 7) & 31, (word >> 12) & 7, (word >> 15) & 31, (word >> 20) & 31, word >> 25
    if op == 0x33 and f3 == 0:
        return f"{'sub' if f7 == 0x20 else 'add'} x{rd}, x{rs1}, x{rs2}"
    if op == 0x13 and f3 == 0:
        return f"addi x{rd}, x{rs1}, {sign_extend(word >> 20, 12)}"
    if op == 0x03 and f3 == 2:
        return f"lw x{rd}, {sign_extend(word >> 20, 12)}(x{rs1})"
    if op == 0x23 and f3 == 2:
        imm = sign_extend(((word >> 25) << 5) | ((word >> 7) & 31), 12)
        return f"sw x{rs2}, {imm}(x{rs1})"
    if op == 0x63 and f3 == 0:
        imm = (((word >> 31) & 1) << 12) | (((word >> 7) & 1) << 11) | (((word >> 25) & 0x3F) << 5) | (((word >> 8) & 0xF) << 1)
        return f"beq x{rs1}, x{rs2}, {sign_extend(imm, 13)}"
    return 'unknown'
```

```python tests
for w, text in [(0x00C58533, 'add x10, x11, x12'), (0x40C58533, 'sub x10, x11, x12'), (0x00A00293, 'addi x5, x0, 10'),
                (0xC0028293, 'addi x5, x5, -1024'), (0x00812503, 'lw x10, 8(x2)'), (0x00A12423, 'sw x10, 8(x2)'),
                (0xFE742A23, 'sw x7, -12(x8)'), (0xFE628EE3, 'beq x5, x6, -4'), (0x00628863, 'beq x5, x6, 16'),
                (0x00944263, 'unknown')]:
    assert disassemble(w) == text, f"{w:#010x} should read '{text}', got '{disassemble(w)}'."
```

::: right
Right. That's the core of every disassembler and emulator: decode the fields, then switch on opcode and funct3.
:::
:::

::: explain
## Why does RISC-V scatter the bits of a branch offset around the instruction word instead of storing them in order?

::: model
The scattering keeps everything else in fixed places. rs1, rs2 and funct3 sit at the same bit positions in every format that has them, so the register file can start reading before the processor even knows what kind of instruction it has. The immediate bits are arranged so that each bit of the offset comes from as few different instruction bits as possible across the formats: bit 31 is always the sign, and most other immediate bits line up between the I, S and B layouts. That makes the immediate generator a handful of multiplexers. The cost falls on software (assemblers, disassemblers and anyone decoding by hand), which is cheap compared with hardware on the critical path.
:::
:::
