Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'rubygems'
- require 'bindata'
- require 'readline'
- class VirtualMachine
- def self.run bytecode
- cells = Array.new
- @plus = 0x1
- @minus = 0x2
- @next = 0x3
- @previous = 0x4
- @read = 0x5
- @print = 0x6
- cell = 0
- ip = 0
- while not bytecode.size == ip
- if cells[cell].nil?
- cells[cell] = 0
- end
- case bytecode[ip]
- when @plus
- cells[cell] += 1
- when @minus
- cells[cell] -= 1
- when @next
- cell += 1
- when @previous
- cell -= 1
- when @read
- cells[cell] = Readline.readline('',true).chomp.to_i
- when @print
- print cells[cell].chr
- end
- ip += 1
- end
- end
- end
- ARGV.each do |file_name|
- if not File.exist? file_name
- puts "File #{file_name} doesn't exist!"
- exit 1
- end
- bytecode = Array.new
- File.open(file_name) do |file|
- file.each_byte do |ch|
- bytecode[bytecode.size] = ch
- end
- end
- VirtualMachine.run bytecode
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement