Skip to content

Instantly share code, notes, and snippets.

@zonque
Created May 9, 2016 09:26
Show Gist options
  • Select an option

  • Save zonque/807464413be91afaa7d74eef2a95781c to your computer and use it in GitHub Desktop.

Select an option

Save zonque/807464413be91afaa7d74eef2a95781c to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
#
# Copyright 2013 Daniel Mack
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
require 'optparse'
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: [options] input-files"
options[:dec] = false
options[:width] = 8
options[:indent] = 2
options[:static] = false
opts.on('-d', '--dec', 'Use decimal output mode (default is hex)') do
options[:dec] = true
end
opts.on('-s', '--static', 'Declare output array static') do
options[:static] = true
end
opts.on('-w', '--width n', 'Number of output colums (defaults to 8)') do |width|
options[:width] = width.to_i
end
opts.on('-i', '--indent n', 'Number of spaces for indent (defaults to 2)') do |indent|
options[:indent] = indent.to_i
end
end
optparse.parse!
indent = " " * options[:indent]
if options[:dec]
fmt = "%d"
else
fmt = "0x%02x"
end
if options[:static]
prefix = "static "
else
prefix = ""
end
ARGV.each do |filename|
content = IO.binread(filename)
offset = 0
name = filename.gsub(/[^a-zA-Z0-9]/, '_')
printf "#{prefix}unsigned char #{name}[] = {\n"
printf indent
while offset < content.length
printf "#{fmt}, ", content[offset].ord
offset += 1
if offset % options[:width] == 0
print "\n" + indent
end
end
print "\n};\n\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment