Added Read/Write function to MC
This commit is contained in:
@@ -2,10 +2,86 @@ namespace CPUSimulation
|
||||
{
|
||||
public class MC
|
||||
{
|
||||
string _name;
|
||||
public MC(string name)
|
||||
|
||||
MemoryBank[] _memoryBanks;
|
||||
int _numberOfMemoryBanks;
|
||||
int _memoryBankSize;
|
||||
|
||||
public MC(int numberOfMemoryBanks, int memoryBankSize = 1024)
|
||||
{
|
||||
_name = name;
|
||||
_numberOfMemoryBanks = numberOfMemoryBanks;
|
||||
_memoryBankSize = memoryBankSize;
|
||||
Bit bit = new Bit();
|
||||
Byte thisByte = new Byte(new Bit[8] { bit, bit, bit, bit, bit, bit, bit, bit });
|
||||
|
||||
_memoryBanks = new MemoryBank[numberOfMemoryBanks];
|
||||
|
||||
for(int i = 0; i < numberOfMemoryBanks; i++)
|
||||
{
|
||||
Byte[] newMemoryBank = new Byte[memoryBankSize];
|
||||
for(int j = 0; j < memoryBankSize; j++)
|
||||
{
|
||||
newMemoryBank[j] = thisByte;
|
||||
}
|
||||
_memoryBanks[i] = new MemoryBank(newMemoryBank);
|
||||
}
|
||||
}
|
||||
|
||||
public Word Read(int address)
|
||||
{
|
||||
AddressOkay(address);
|
||||
Byte[] byteData = new Byte[_numberOfMemoryBanks];
|
||||
for (int i = 0; i < _numberOfMemoryBanks; i++)
|
||||
{
|
||||
byteData[i] = _memoryBanks[i].Read((byte)address);
|
||||
}
|
||||
return new Word(byteData);
|
||||
}
|
||||
|
||||
public void Write(int address, Word data)
|
||||
{
|
||||
AddressOkay(address);
|
||||
Byte[] byteData = data.GetBytes();
|
||||
int byteCount = data.GetByteCount();
|
||||
Byte[] bytesToWrite;
|
||||
if (byteCount < _numberOfMemoryBanks)
|
||||
{
|
||||
int numberOfPaddingBytes = _numberOfMemoryBanks - byteCount;
|
||||
bytesToWrite = new Byte[_numberOfMemoryBanks];
|
||||
for (int i = 0; i < _numberOfMemoryBanks; i++)
|
||||
{
|
||||
if (i < numberOfPaddingBytes)
|
||||
{
|
||||
bytesToWrite[i] = new Byte(new Bit[8]{ new Bit(false), new Bit(false), new Bit(false), new Bit(false), new Bit(false), new Bit(false), new Bit(false), new Bit(false) });
|
||||
}
|
||||
else
|
||||
{
|
||||
bytesToWrite[i] = byteData[i - numberOfPaddingBytes];
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (data.GetByteCount() > _numberOfMemoryBanks)
|
||||
{
|
||||
throw new ArgumentException($"Data must consist of {_numberOfMemoryBanks} bytes or less.");
|
||||
}
|
||||
else
|
||||
{
|
||||
bytesToWrite = byteData;
|
||||
}
|
||||
|
||||
|
||||
for (int i = 0; i < _numberOfMemoryBanks; i++)
|
||||
{
|
||||
_memoryBanks[i].Write((byte)address, bytesToWrite[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void AddressOkay(int address)
|
||||
{
|
||||
if (address < 0 || address >= _memoryBankSize)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(address), $"Address must be between 0 and {_memoryBankSize - 1}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user