10進数を2進数と16進数に変換する
"%b" % num "%x" % num
ってな具合に、フォーマットを指定すればすごい簡単なのだけど、
それじゃつまらないのでそれ以外の方法でやってみた。
2進数はまあこれで大丈夫。
でも16進数はうまくいってない・・・。
hex << 'F' で hex の末尾に 'F' が追加されるはずなのに、
なぜか '15' が追加されている。。
なんで・・・。
class Fixnum def to_b num = self bin = "" while num > 0 bin << (num % 2).to_s num /= 2 end bin.reverse end def to_x num = self hex = "" while num > 0 temp = (num % 16).to_s case temp when 10 hex << 'A' when 11 hex << 'B' when 12 hex << 'C' when 13 hex << 'D' when 14 hex << 'E' when 15 hex << 'F' else hex << temp.to_s end num /= 16 end hex.reverse end end while line = gets line.chomp! next unless /\d+/ =~ line num = line.to_i puts num.to_b puts num.to_x puts end
追記
このエントリを書いてから、
貼り付けたソースを見てみたらすぐに何が原因か分かった。
ぐあーなんておれは馬鹿なんだーーっ!
class Fixnum def to_b num = self bin = "" while num > 0 bin << (num % 2).to_s num /= 2 end bin.reverse end def to_x num = self hex = "" while num > 0 temp = (num % 16) #.to_s ← ここで .to_s してるのが問題だった!! case temp when 10 hex << 'A' when 11 hex << 'B' when 12 hex << 'C' when 13 hex << 'D' when 14 hex << 'E' when 15 hex << 'F' else hex << temp.to_s end num /= 16 end hex.reverse end end while line = gets line.chomp! next unless /\d+/ =~ line num = line.to_i puts num.to_b puts num.to_x puts end
追記の追記
コメントから、進数の変換にはInteger#to_sが使えることを知った。
以下はマニュアルからコピペしたもの。
色々とやり方はあるもんだなぁー。TIMTOWTDI!
p 10.to_s(2) # => "1010" p 10.to_s(8) # => "12" p 10.to_s(16) # => "a" p 35.to_s(36) # => "z"