Simple 8-Bit Emu

new topic     » topic index » view thread      » older message » newer message

Here is a very simple 8-Bit emulator in Euphoria

include std/machine.e 
include std/math.e 
 
constant MEM_SIZE = 256 
sequence memory = repeat(0,MEM_SIZE) 
 
integer A = 0 --Accumlator 
integer PC = 0 --Program counter 
integer running = 1 
 
--Opcodes 
constant LDA = 1, --Load A from memory 
		STA = 2, --Store A to memory 
		ADD = 3, --Add value from memory 
		JMP = 4, --Jump to address 
		HLT = 5, --Halt 
               SUB = 6 
		 
-- Sample program: 
-- Address: Instruction 
-- 00: LDA 10     ; A = memory[10] 
-- 02: ADD 11     ; A += memory[11] 
-- 04: STA 12     ; memory[12] = A 
-- 06: HLT 
-- 10: 5          ; Value 1 
-- 11: 3          ; Value 2 
 
memory[1] = LDA 
memory[2] = 10 
memory[3] = ADD --Change to sub if you want to subtract 
memory[4] = 11 
memory[5] = STA 
memory[6] = 12 
memory[7] = HLT 
memory[11] = 5 
memory[12] = 3 
 
procedure run() 
	while running = 1 do 
		integer opcode = memory[PC + 1] 
		integer operand = memory[PC + 2] 
		 
		if opcode = LDA then 
			A = memory[operand + 1] 
			PC += 2 
			 
		elsif opcode = STA then 
			memory[operand + 1] = A 
			PC += 2 
			 
		elsif opcode = ADD then 
			A+= memory[operand + 1] 
			A = and_bits(A,255) 
			PC += 2  
 
               elsif opcode = SUB then 
			A -= memory[operand + 1] 
			if A < 0 then 
				A += 256 
			end if 
			A = and_bits(A,255) 
			PC += 2 
			 
		elsif opcode = JMP then 
			PC = operand 
			 
		elsif opcode = HLT then 
			running = 0 
			else 
				puts(1,"Unknown opcode!\n") 
				running = 0 
		end if 
	end while 
end procedure 
 
run() 
printf(1,"Final value in A: %d\n",A) 
printf(1,"memory[12] = %d\n",memory[13]) 
new topic     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu