Skip to content

Instantly share code, notes, and snippets.

@jpmckinney
Created December 27, 2010 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmckinney/756380 to your computer and use it in GitHub Desktop.
Save jpmckinney/756380 to your computer and use it in GitHub Desktop.
Convert between plain text JavaScript and C char array
# coding: utf-8
# blog post: http://blog.slashpoundbang.com/post/2488598258/running-javascript-from-the-command-line-with-v8
abort "usage: #{$0} filename.h\n #{$0} filename.js prefix" unless ARGV[0]
abort "ERROR: Couldn't open '#{ARGV[0]}' for reading" unless File.exist?(ARGV[0])
abort "ERROR: Prefix is required if input is JavaScript" if ARGV[0][/js$/] && !ARGV[1]
if ARGV[0][/js$/]
puts "const char #{ARGV[1]}_code[] = {\n #{File.read(ARGV[0]).unpack('U*').map{|i| i == 8212 ? [226, 128, 148] : i }.flatten.each_slice(16).map{ |a| a.map{ |i| "0x%02x" % i }.join(',') }.join(",\n ") },0x00\n};"
else
puts File.read(ARGV[0])[/(0x.+),0x00/m, 1].split(',').reduce('') { |string,x| string += x.hex.chr }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment