Skip to content

Instantly share code, notes, and snippets.

@kols
Created June 26, 2012 18:22
Show Gist options
  • Save kols/2997719 to your computer and use it in GitHub Desktop.
Save kols/2997719 to your computer and use it in GitHub Desktop.
Convert hex string to ruby string
#!/usr/bin/env ruby
def convert_hexstr(str, start=0, index=nil)
index ||= str.length
hexstr = str[start, index]
ar = []
hexstr.scan(/\\x../).each do |s|
ar << s.gsub('\\', '0').to_i(16)
end
ar.empty? ? str : ar.pack('C*').force_encoding('utf-8')
end
def convert(str)
non_hexstr_start += 4 if
non_hexstr_start = str.index(/(\\x..)([^(\\x..)]+)(\\x..)/)
hexstr_start, hexstr_end = str.index(/\\x../), str.rindex(/\\x../)
if ! non_hexstr_start
if hexstr_start || hexstr_end
hexstr_length = hexstr_end + 3 - hexstr_start + 1
str[hexstr_start, hexstr_length] = convert_hexstr(str)
end
str
else
hexstr_length = non_hexstr_start - hexstr_start
parsed_str_before_non_hexstr = convert_hexstr(str, hexstr_start,
hexstr_length)
str[hexstr_start, hexstr_length] = parsed_str_before_non_hexstr
convert(str)
end
end
def main
f_name = ARGV[0]
new_lines = Array.new
File.open(f_name) do |f|
f.each do |line|
new_lines << convert(line)
end
end
File.open(f_name, 'w') { |f| f.write new_lines.join }
end
def test
puts convert('\xE7\x94\xA8 Python \xE5\xBB\xBA\xE8\x8B\xB1\xE8\xAF\xAD\xE5\x8D\x95\xE8\xAF\x8D\xE8\xA1\xA8')
puts convert('\xE8\xAE\xA9\xE4\xBD\xA0\xE7\x9A\x84MSN\xE5\x89\x8D\xE9\x9D\xA2\xE5\xA4\x9A\xE4\xB8\xAAIAM\xE7\x9A\x84\xE6\x96\xB9\xE6\xB3\x95[\xE8\xBD\xAC]')
puts convert('Wordpress on dotcloud')
puts convert('Eng\xE7\x94\xA8lish')
end
#test
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment