Hatena::ブログ(Diary)

gan2 の Ruby 勉強日記 このページをアンテナに追加 RSSフィード

この日記のはてなブックマーク数 PV/ 870407 Subscribe with livedoor Reader 役立つリンク集

2007-06-03

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"

muscovyduckmuscovyduck 2007/06/04 05:53 整数(10進数)からx進数を得るには、Integer#to_s(x)が使えますよ。

15.to_s(2) #=> ”1111”
15.to_s(16) #=> ”f”

gan2gan2 2007/06/04 13:54 なんとっ!
to_sにはそんな使い方があったんですね。
便利ですねー。

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証