149 lines
3.6 KiB
C#
149 lines
3.6 KiB
C#
using System;
|
|
|
|
namespace CPUSimulation
|
|
{
|
|
public class Bit
|
|
{
|
|
bool _value;
|
|
public Bit(bool value = false)
|
|
{
|
|
_value = value;
|
|
}
|
|
public bool GetValue()
|
|
{
|
|
return _value;
|
|
}
|
|
}
|
|
public class Byte
|
|
{
|
|
Bit[] _bits;
|
|
public Byte(Bit[] bits)
|
|
{
|
|
if (bits.Length != 8)
|
|
{
|
|
throw new ArgumentException("A byte must consist of exactly 8 bits.");
|
|
}
|
|
_bits = bits;
|
|
}
|
|
|
|
public Bit[] GetBits()
|
|
{
|
|
return _bits;
|
|
}
|
|
}
|
|
|
|
public class MemoryBank
|
|
{
|
|
Dictionary<string, Byte> _bytes;
|
|
public MemoryBank(Byte[] bytes)
|
|
{
|
|
_bytes = new Dictionary<string, Byte>();
|
|
for (int i = 0; i < bytes.Length; i++)
|
|
{
|
|
_bytes[new Address((Int16)i).ToString()] = bytes[i];
|
|
}
|
|
}
|
|
|
|
public Byte Read(string address)
|
|
{
|
|
return _bytes[address];
|
|
}
|
|
|
|
public void Write(string address, Byte data)
|
|
{
|
|
_bytes[address] = data;
|
|
}
|
|
}
|
|
|
|
public class Address
|
|
{
|
|
Byte _highByte;
|
|
Byte _lowByte;
|
|
public Address(Byte highByte, Byte lowByte)
|
|
{
|
|
_highByte = highByte;
|
|
_lowByte = lowByte;
|
|
}
|
|
|
|
public Address (Int16 address)
|
|
{
|
|
byte highByteValue = (byte)(address / 256);
|
|
byte lowByteValue = (byte)(address % 256);
|
|
_highByte = new Byte(GetBitsFromByte(highByteValue));
|
|
_lowByte = new Byte(GetBitsFromByte(lowByteValue));
|
|
}
|
|
|
|
public Address(string address)
|
|
{
|
|
if (address.Length != 16)
|
|
{
|
|
throw new ArgumentException("Address string must be exactly 16 characters long.");
|
|
}
|
|
Bit[] highByteBits = new Bit[8];
|
|
Bit[] lowByteBits = new Bit[8];
|
|
for (int i = 0; i < 8; i++)
|
|
{
|
|
highByteBits[i] = new Bit(address[i] == '1');
|
|
lowByteBits[i] = new Bit(address[i + 8] == '1');
|
|
}
|
|
_highByte = new Byte(highByteBits);
|
|
_lowByte = new Byte(lowByteBits);
|
|
}
|
|
|
|
private Bit[] GetBitsFromByte(byte value)
|
|
{
|
|
Bit[] bits = new Bit[8];
|
|
for (int i = 0; i < 8; i++)
|
|
{
|
|
bits[7 - i] = new Bit((value & (1 << i)) != 0);
|
|
}
|
|
return bits;
|
|
}
|
|
|
|
public override string ToString()
|
|
{
|
|
string addressString = "";
|
|
foreach (Bit bit in _highByte.GetBits())
|
|
{
|
|
addressString += bit.GetValue() ? "1" : "0";
|
|
}
|
|
foreach (Bit bit in _lowByte.GetBits())
|
|
{
|
|
addressString += bit.GetValue() ? "1" : "0";
|
|
}
|
|
return addressString;
|
|
}
|
|
}
|
|
|
|
public class Word
|
|
{
|
|
Byte[] _bytes;
|
|
public Word(Byte[] bytes)
|
|
{
|
|
_bytes = bytes;
|
|
}
|
|
|
|
public int GetByteCount()
|
|
{
|
|
return _bytes.Length;
|
|
}
|
|
|
|
public Byte[] GetBytes()
|
|
{
|
|
return _bytes;
|
|
}
|
|
|
|
public override string ToString()
|
|
{
|
|
string wordString = "";
|
|
foreach (Byte b in _bytes)
|
|
{
|
|
foreach (Bit bit in b.GetBits())
|
|
{
|
|
wordString += bit.GetValue() ? "1" : "0";
|
|
}
|
|
}
|
|
return wordString;
|
|
}
|
|
}
|
|
} |