Skip to content

Instantly share code, notes, and snippets.

@vinniefranco
Created October 30, 2013 08:21
Show Gist options
  • Save vinniefranco/7228896 to your computer and use it in GitHub Desktop.
Save vinniefranco/7228896 to your computer and use it in GitHub Desktop.
A binary helper for bitwise operations. Outputs: base10, hex, and binary representation of register value. Inputs: Base10: Anything below 999 is read into "register" as a value. Binary: Accepts anything over a half bit. e.g. 0111, 101010, and 1111000, etc. Register can be altered by bit shifting through AND, OR, and XOR operations.
require 'readline'
class String
# colorization
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
def red
colorize(31)
end
def green
colorize(32)
end
def yellow
colorize(33)
end
end
class BinaryHelper
OPERATORS = { "&=" => :and, "|=" => :or, "^=" => :xor }
def initialize
@value = 0
end
def or(value)
@value |= value
end
def and(value)
@value &= value
end
def xor(value)
@value ^= value
end
def assign(value)
@value = value
end
def match_operator(asn_operand)
OPERATORS[asn_operand]
end
def result
output = "#{binary}".green
output << " #{hex}".yellow
output << " #{@value}".red
output
end
def hex
value_out "x", 16, 2
end
def binary
value_out "b", 2, 8
end
def value_out(leader, base, rjust)
"0#{leader}#{@value.to_s(base).rjust(rjust, '0')}"
end
def run_instruction(instruction = "")
return result if instruction.empty?
if legal? instruction
execute instruction
else
error_on instruction
end
end
def execute(instruction)
operator = match_operator instruction[0..1]
if operator
value = eval parse_binary(instruction[3..-1])
send operator, value
else
@value = eval parse_binary(instruction)
end
result
end
def error_on(instruction)
"I don't understand: '#{instruction}'"
end
def legal?(instruction)
!(instruction =~ /[^0-9\(\)\<\>\~\^\=&|\ ]/)
end
def parse_binary(str)
return str unless str =~ /[0-1]{4,8}/
subs = {}
matches = str.scan(/[0-1]{4,8}/)
matches.each { |match| subs[match] = match.to_i(2).to_s }
subs.each { |binary,integer| str.gsub! binary, integer }
str
end
end
helper = BinaryHelper.new
prompt = "bindur".yellow + "➜ ".red
begin
while buf = Readline.readline(prompt, true)
Readline::HISTORY.pop if buf =~ /^\s*$/ or Readline::HISTORY.to_a[-2] == buf
exit if buf == "quit" || buf == "exit"
puts helper.run_instruction(buf)
end
rescue Interrupt
puts "See you later!"
exit
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment