Skip to content
BetterDL

Instruction encoding

Also called: encoding an instruction, machine code, machine language

Turning an instruction such as STORE D into its binary word by placing each field's bits in the instruction format.

Instruction encoding is the step from a written instruction to the bits the CPU actually stores and fetches: machine code.

For Tiny8 it's two lookups:

  1. The opcode for the mnemonic, as 4 bits. (STORE = 2 = 0010.)
  2. The address, as 4 bits. (D = 13 = 1101.)

Put the opcode in the high nibble and the address in the low nibble: 0010 1101, which is 2D in hex. Since each field is exactly one hex digit, you can encode Tiny8 instructions straight into hex.

The reverse, from bits to meaning, is instruction decoding. A quick check after encoding is to decode your answer back.

On other machines the fields have other widths, so encode in binary first, then group into hex digits. For example, a 6-bit opcode and a 10-bit address don't line up with hex digits.

0
128
1
64
0
32
0
16
1
8
0
4
0
2
1
1

Worked examples

Example

Encoding SUB 9

Encode SUB 9 for Tiny8.

  1. 1.

    SUB = opcode 4 = 0100.

  2. 2.

    Address 9 = 1001.

  3. 3.

    Word: 0100 1001 = 49 (shown above).

  4. 4.

    Check: left digit 4 = SUB, right digit 9 = the address.

Example

A field that doesn't fit hex

A machine has 12-bit instructions: a 4-bit opcode and an 8-bit address. Encode opcode 9 with address 37.

  1. 1.

    Opcode 9 = 1001.

  2. 2.

    Address 37 = 32 + 4 + 1 = 00100101.

  3. 3.

    Word: 1001 0010 0101 = 925 in hex.

Common mistakes

  • Putting the address first. The opcode is the high field.

  • Dropping leading zeros. LOAD 0 is 10, not 1.

  • Writing the address in decimal. Address 11 is B.

Practice Instruction encoding

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Instruction encoding is taught in Basic CPU / Computer Architecture.