Skip to content

Instantly share code, notes, and snippets.

@SpringMT
Forked from masquaremo/str_num_sample.rb
Created October 16, 2017 02:52
Show Gist options
  • Save SpringMT/5fbe37cebf11382df01f40e7b03f6a48 to your computer and use it in GitHub Desktop.
Save SpringMT/5fbe37cebf11382df01f40e7b03f6a48 to your computer and use it in GitHub Desktop.
Rubyで文字列と数値を相互に変換するメソッドとかのまとめ
#!/usr/bin/ruby
#数値を16進数文字列に
p 65.to_s(16) #=> "41"
#数値をASCII文字に
p 65.chr #=> "A"
#文字列を16進数とみなして数値に
p "41".hex #=> 65
p "0xFF".hex #=> 255
p "41".to_i(16) #=> 65
p "0x41".to_i(16) #=> 65
#文字列を10進数とみなして数値に
p "41".to_i #=> 41
p "0x41".to_i #=> 0, 数字ではないところまでを変換する
#ASCII文字を数値に
p "A".ord #=> 65
p "AB".ord #=> 65, 最初の1文字だけが対象
#文字列を数値配列に
p "ABCDEFG\x41\x42".unpack("C*")
#=> [65, 66, 67, 68, 69, 70, 71, 65, 66]
#文字列を16進数ダンプ風
p "ABCDEFG\x41\x42".unpack("H*").pop.scan(/[0-9a-f]{2}/).join(" ")
#=> "41 42 43 44 45 46 47 41 42"
#16進数ダンプ風文字列を文字列に
p "41 42 43 44 45 46 47 41 42".split.collect {|c| c.hex}.pack("C*")
#=> "ABCDEFGAB"
p "41 42 43 44 45 46 47 41 42".split.collect {|c| c.hex.chr}.join
#=> "ABCDEFGAB"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment