#include <stdio.h>
#define EXCEPTION_STACK_LENGTH 8
#define REGISTER_COUNT 16
#define MEMORY_CAPACITY 65536
#define ACCESS_VIOLATION 4
#define UNKNOWN_ERROR 8
#define REGISTER_PC (REGISTER_COUNT - 4)
#define REGISTER_SP (REGISTER_COUNT - 3)
#define REGISTER_FP (REGISTER_COUNT - 2)
#define REGISTER_ST (REGISTER_COUNT - 1)
typedef int WORD32;
typedef unsigned int UWORD32;
typedef unsigned short UWORD16;
typedef short WORD16;
typedef unsigned char BYTE8;
typedef char CHAR8;
BYTE8 Memory[] = {
0x01,0x00,0x00,0x05,
0x02,0xC0,0x00,0x00,
0x01,0x00,0x7C,0x08,
0x02,0xC1,0x00,0x00,
0x08,0x10,0x00,0x00,
0x03,0xC0,0x00,0x0F,
0x00,0x00,0x00,0x00
};
UWORD16 Register[REGISTER_COUNT];
UWORD32 Instruction;
void ThrowException(WORD32 Code)
{
}
void CheckMemoryAddress(UWORD32 Address)
{
if (Address >= MEMORY_CAPACITY)
ThrowException(ACCESS_VIOLATION);
};
void CheckRegisterIndex(BYTE8 Index)
{
if (Index >= REGISTER_COUNT)
ThrowException(ACCESS_VIOLATION);
};
void CheckProgramCounter(UWORD32 Amount)
{
CheckMemoryAddress(Register[REGISTER_PC] + (Amount));
};
// ----
UWORD32 SwapWord32Order (UWORD32 Word) {
UWORD32 TemporaryData = 0;
TemporaryData = ((Word & 0xFF) << 24) | ((Word & 0xFF00) << 8);
TemporaryData = TemporaryData | ((Word & 0x00FF0000) >> 8) | ((Word & 0xFF000000) >> 24);
return TemporaryData;
};
void IncrementRegister (BYTE8 Index, UWORD16 Amount) {
CheckRegisterIndex(Index);
Register[Index] += Amount;
};
void DecodeInstruction(void)
{
CheckProgramCounter(sizeof(UWORD32));
Instruction = 0;
Instruction = *(UWORD32*) &Memory[Register[REGISTER_PC]];
Instruction = SwapWord32Order(Instruction);
printf("%08X\n", Instruction);
IncrementRegister (REGISTER_PC, sizeof (UWORD32));
};
int main(int argc, char **argv)
{
int cnt = sizeof(Memory)/sizeof(UWORD32);
for (int i = 0; i < cnt; i++)
DecodeInstruction();
return 0;
}
prints 01000005
02C00000
01007C08
02C10000
08100000
03C0000F
00000000