Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
文字列を \xXX 形式に変換する
#!/usr/bin/env ruby
def str2x(str)
str.unpack("H*").first.scan(/[0-9a-z]{2}/).map{ |x| '\x' + x.upcase }.join
end
str = ARGV[0]
unless str
puts <<USAGE
Usage: ruby #{$0} STRING
USAGE
end
puts str2x(str)
# ruby str2x.rb 本日は晴天なり
# => \xE6\x9C\xAC\xE6\x97\xA5\xE3\x81\xAF\xE6\x99\xB4\xE5\xA4\xA9\xE3\x81\xAA\xE3\x82\x8A
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment