Code covered by the BSD License  

Highlights from
Extended Brookshear Machine emulator and assembler

image thumbnail
from Extended Brookshear Machine emulator and assembler by David Young
Emulator and assembler for a simple computer, a teaching aid for computer science courses.

loadmem(machine, text)
function machine = loadmem(machine, text)
%LOADMEM loads instructions from text into memory
%   MACHINE = LOADMEM(MACHINE, TEXT) takes a BM MACHINE and a string TEXT,
%   and returns and updated machine with the instructions specified by the
%   string loaded into memory, provided the string contains valid
%   instructions in hex.
%
%   The format of the string is as specified for a memory file in BMHELP.M
%
%   See also: BMHELP

%   Copyright 2008 University of Sussex and David Young

% remove comments and white space other than newlines
text = regexprep(text, {'//[^\n]*(?:\n|$)', '[ \t\f\r\v]*'}, {'\n', ''});
% split into lines
lines = regexp(text, '\n*', 'split');

mem = machine.memory;
addr = 0;
for i = 1:length(lines)
    line = lines{i};
    ad = regexp(line, '(?<a>[^:]*):(?<d>.*)', 'names');

    if ~isempty(ad)     % have an address
        if ~isequal(length(ad.a), 2)
            throw(MException('bmachine:loadmem:badaddr', ...
                ['Address not 2 characters in:' line]));
        end
        try
            addr = hex2dec(ad.a);   % set address
        catch ME
            if isequal(ME.identifier, 'MATLAB:hex2dec:IllegalHexadecimal')
                throw(MException('bmachine:loadmem:badaddr', ...
                    ['Address has non-hex character in:' line]));
            else
                rethrow(ME)
            end
        end
        line = ad.d;
    end

    if mod(length(line), 2)
        throw(MException('bmachine:loadmem:baddata', ...
            ['Data has odd number of characters in:' line]));
    end
    for j = 1:2:length(line)
        try
            v = hex2dec(line(j:j+1));
        catch ME
            if isequal(ME.identifier, 'MATLAB:hex2dec:IllegalHexadecimal')
                throw(MException('bmachine:loadmem:baddata', ...
                    ['Data has non-hex character in:' line]));
             else
                rethrow(ME)
            end
        end
        if addr >= length(mem)
            throw(MException('bmachine:loadmem:overrun', ...
                ['Too much data to fit in memory in:' line]));
        end
        mem(addr+1) = v;
        addr = addr + 1;
    end
end

machine.memory = mem;
end

Contact us at files@mathworks.com