Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Main()
- {
- long[] literals = new long[]
- {
- 1,
- 2
- };
- byte[] instructions = new byte[]
- {
- PUSH, 0,
- PUSH, 1,
- ADD,
- RET
- };
- Compile(literals, instructions).Dump();
- }
- const byte PUSH = 0;
- const byte ADD = 1;
- const byte RET = 2;
- static long Compile(long[] literals, byte[] instructions)
- {
- Stack<long> stack = new Stack<long>();
- int instructionPointer = 0;
- while (true)
- {
- switch (instructions[instructionPointer])
- {
- case PUSH:
- ++instructionPointer;
- stack.Push(literals[instructions[instructionPointer]]);
- break;
- case ADD:
- stack.Push(stack.Pop() + stack.Pop());
- break;
- case RET:
- return stack.Pop();
- }
- instructionPointer++;
- }
- }
Add Comment
Please, Sign In to add comment