LoginSignup
5
2

More than 1 year has passed since last update.

【Ruby】10進数 ⇔ n進数の変換

Posted at

n進数の文字列を10進数の数値へ変換する → String#to_iメソッド

# 2進数を10進数に変換
puts '101'.to_i(2)
#=> 5

# 5進数を10進数に変換
puts '144'.to_i(5)
#=> 49

# 16進数を10進数に変換
puts 'FA'.to_i(16)
#=> 250

10進数の数値をn進数の文字列へ変換する → Integer#to_s

# 10進数を2進数に変換
puts 1010.to_s(2)
#=> '1111110010'

# 10進数を8進数に変換
puts 1010.to_s(8)
#=> '1762'

# 10進数を16進数に変換
puts 1010.to_s(16)
#=> '3F2'

5
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2