#!/usr/bin/ruby class Hex2Bin attr_accessor :data; def initialize @data = "" @invert = false end # store the result of the contained block of code # into a buffer def block temp = @data inverted = @invert @invert = false; @data = "" yield newdata = @data @data = temp @invert = inverted; return newdata end # invert the contained block of code def invert @invert = !@invert; yield @invert = !@invert; end # reverse the bytes in the contained # block of code def reverse_bytes temp = block{ yield } binary(temp.reverse) end # reverse the bits in the contained # block of code def reverse_bits reverse_bytes{ temp = block{ yield; } binary(temp.unpack("B*").pack("b*")) } end # chunk the buffer specified into blocks of # the specified size and then iterate # over them def each_chunk(data, size) (1..(data.length/size.to_f).ceil).each{ |count| start = (count - 1)*size last = (count)*size - 1; if(last >= data.length) then last = data.length() -1 end yield(data[start..last]) } end # repeat the contained code # the specified number of times def repeat( count ) (1..count).each{ |index| yield(index)} end # write the specified binary data def binary(binary_str) if(@invert) then binary_str = binary_str.unpack("C*").collect{|x| ~x}.pack("C*") end @data << binary_str end # convert the specified hex string # to binary data def hex(hex_str) binary( hex_str.gsub(/\s/,'').to_a.pack("H*") ) end # write the specified ascii string as # ascii data def ascii(ascii_string) binary( ascii_string ) end # write the specified value as a byte def byte(value) binary([value].pack("C1")) end def get_binding() return binding end # shift the data generated by the contained # code by the specified number of bits # and use the fill bits provided to fill in # the left and right edges to byte boundaries def shift_right(bits, fill) temp = block{ yield } fill = [fill].pack("C").unpack("B*")[0]; data = fill[0, bits] + temp.unpack("B*")[0] + fill[bits, 8-bits] binary([data].pack("B*")) end end context = Hex2Bin.new(); eval(STDIN.read, context.get_binding) STDOUT.write(context.data);