def encode_mem_instr(instr):
    """
    Encode an M-type instruction as a number.
    :param instr: list, M-type instruction operands, e.g. ['ldw', 'r1', 'r2', '10']
    :return: int, encoded instruction.
    """
    hex_instr = 0

    # Decode.
    cmd = instr[0]
    dst = instr[1]
    src = instr[2]
    off = instr[3]

    # Encode opcode.
    if cmd == 'ldb':
        hex_instr += 0x10 << 25
    elif cmd == 'ldw':
        hex_instr += 0x11 << 25
    elif cmd == 'stb':
        hex_instr += 0x12 << 25
    else:
        hex_instr += 0x13 << 25

    # Encode destination register.
    dst_reg = int(''.join(c for c in dst if c.isdigit()), 16)
    hex_instr += dst_reg << 20

    # Encode source register.
    src_reg = int(''.join(c for c in src if c.isdigit()), 16)
    hex_instr += src_reg << 15

    # Encode offset.
    off_val = int(off, 16)
    hex_instr += off_val

    return hex_instr