Skip to content

Instantly share code, notes, and snippets.

@takeshy takeshy/hex2bin.rb
Created Apr 22, 2015

Embed
What would you like to do?
HEX文字列をbinaryに変換する
#!/bin/env ruby
$HEX = false
if ARGV[0] == "-x"
$HEX = true
ARGV.shift
end
if ARGV.length != 1
puts "#{$0} outputfile"
exit -1
end
unless file = File.open(ARGV[0],"wb")
puts "#{$0} outputfile"
puts "#{ARGV[0]} can't write"
exit -1
end
begin
datas = []
if $HEX
STDIN.each do |line|
datas.concat(line.scan(/[\da-zA-Z]{2}/).map do|i| i.hex end)
end
else
STDIN.each do |line|
datas.concat(line.scan(/[\d]{1,3}/).map do|i| i.to_i end)
end
end
file.write(datas.pack("C*"))
ensure
file.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.