1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyで2進数を計算する方法はとても簡単

Last updated at Posted at 2020-11-28

ruby 2.7.0の記事です

10進数を2進数に変換する方法

以下、私の試行錯誤の結果です

def Binary(num)
 array1 = [] #1になる桁を左から数えた数が入ります 44の場合(6,4,3) つまり(101100)
  while num > 0
    array2 = [] #2で割った数が入ります
    n_i = num
    while n_i > 0 #整数型は小数点を含まない。1/2=0と出力される(0.5にはならない)
      n_i = n_i / 2
      array2 << n_i
    end
    num = num - (2 ** (array2.length - 1)) #array2.lengthで桁を出します 10進数に戻して、最初の数から引きます
    array1 << array2.length #1になる桁数を加えます
  end

  i = 1
  b_a = []
  array1[0].times do #array1[0]に桁が入ります。1か0を配列b_aに入力します
    if array1.include?(i)
      b_a << 1
    else
      b_a << 0
    end
    i += 1
  end

  b_a.reverse.each do |s| #配列をprintで連続して表示します
    print s
  end
  print "\n" #printの改行コードを入力
end

puts "2進数にしたい値を入力してください"
num = gets.to_i
Binary(num)

以下@kts_hさんのコメントを元に追加

num = 44
num.to_s(2) #=> "101100"

puts "2進数にしたい値を入力してください"
num = gets.to_i # 整数にする 仮に44と入力した場合
puts Binary = num.to_s(2) #=>101100 文字列として出力

puts "取り出したい桁を入力してください"
n = gets.to_i #例えば6桁目”6”と入力
puts Binary.slice(-n) #今回はn=6となり、”1”が表示される

# メソッドとして定義したい場合
def Binary(num)
 puts num.to_s(2)
end
  • inspectメソッドを使わず計算式で定義したい場合

  • divmodメソッド

divmod(other) -> [Numeric]
self == other * q + r
other > 0 のとき: 0 <= r < other,
other < 0 のとき: other < r <= 0,
q は整数
公式ドキュメント(Numericクラスdivmod)

11.divmod(3) #=> [3, 2] 公式リファレンスより

def Binary(num)
  acc = []
  while num > 0
    num, mod = num.divmod(2) #numには2で割った数が入ります
    acc << mod #2で割った余りを配列に加えます  つまり1or0です
  end
  answer = acc.reverse!.join #accの値をreverse!で逆にする  joinで値を続けて表示する
  puts answer
end
1
0
4

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?