Last active
August 4, 2018 23:45
-
-
Save Miouyouyou/56e4ae198035d8e9c80ffe7708611735 to your computer and use it in GitHub Desktop.
Binary file to C int array in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ruby | |
require "fileutils" | |
MAX_NUMBERS_PER_LINE = 4 | |
if ARGV.length != 1 | |
puts "./convert.rb path/to/filename > output.c" | |
abort | |
end | |
filename = ARGV[0] | |
unless File.exists?(filename) | |
puts "#{filename} was not found :C" | |
abort | |
end | |
if File.size(filename) < 4 | |
puts "#{filename} size should not be less than 4 bytes." | |
abort | |
end | |
regs = File.read(filename).unpack("I<*") | |
# Start the array definition | |
output = "int regs[#{regs.length}] = {" | |
# Output each integer as an hexadecimal value | |
numbers_per_line = 0 | |
regs.each {|int| | |
output << "\n\t" if (numbers_per_line == 0) | |
output << ("0x%08x, " % int) | |
numbers_per_line += 1 | |
# We could warp power of 2 with &= | |
# But let's avoid smart-ass technics on snippets | |
numbers_per_line = 0 if numbers_per_line == MAX_NUMBERS_PER_LINE | |
} | |
# Remove the last comma | |
output[output.rindex(","), 1] = "" | |
# Closes the array definition | |
output << "\n};\n" | |
# Output the array definition we generated | |
puts output | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment