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

10 進数から 2 進数に変換

Posted at

去年、高校数学で勉強した2進数がでてきた!

今回はコードの解説と、2進数への変換方法を整理するよ。


問題概要

整数 N(10進数)が与えられる。これを2進数に変換して出力せよ。


入力例:

4

出力例:

100




✅OK例:

const rl = require('readline').createInterface({input:process.stdin});

rl.once('line', (input) => {
    
    const N = Number(input);

    // 2進数を作るための配列
    let binary = [];

    // Nが0になるまでループ
    // ループ内で2で割った余りを順に配列に追加する
    for(let temp = N; temp > 0; temp = Math.floor(temp / 2)){
         binary.push(temp % 2);
    }
    
    // 配列の順番が逆なので、reverse()で逆順に
    // join('')で1つの文字列にして出力
    console.log(binary.reverse().join(''));
 
 
  rl.close();
});
  • binary : 配列に余りを順に追加
  • Math.floor() : で小数部分を切り捨てながら2で割り続ける
  • binary.reverse() : で逆順に(下位ビット→上位ビット)
  • join'') : で配列を1つの文字列に結合



📒10進数から2進数への変換の仕組み

【手順】

1️⃣ 2で割り続ける

  • 数字を 2 で割る(商を求める)
  • 余り(0 または 1)を記録する

2️⃣ 商が 0 になるまで繰り返す

  • 割り算の商を次に割る数にして、再び 2 で割る
  • 余りをどんどん記録する

3️⃣ 出てきた余りを逆順に並べる

  • 最初に出てきた余りが 2進数の「下の桁(下位ビット)」だから
  • 最後に出てきた余りが「上の桁(上位ビット)」になる

【例】10進数 13 の場合

1️⃣ 13 ÷ 2 = 6…余り 1

2️⃣ 6 ÷ 2 = 3…余り 0

3️⃣ 3 ÷ 2 = 1…余り 1

4️⃣ 1 ÷ 2 = 0…余り 1

✅ 商が 0 になったので終了
✅ 余りの並び:1, 0, 1, 1
✅ 逆順に並べる → 1101

つまり、13(10進数) = 1101(2進数) となる!


なぜこの方法でうまくいくのか?

👉 10進数の数字を、2の累乗の組み合わせとして表していくから!

例えば、13 なら:

13 = 1 × 8(=2³) + 1 × 4(=2²) + 0 × 0(=2¹) + 1 × 1(=2⁰)

つまり、2進数で「1101」と表す(2³, 2², 2⁰ のところに 1 が立つ)



【まとめ】

✅ 2で割り続ける
✅ 余りを記録する(0 or 1)
✅ 逆順に並べる

これで、10進数 → 2進数変換ができる!




僕の失敗談(´;ω;`)と解決法🐈





おまけ:✅OK例2:toString()

console.log(N.toString(2)); // 2進数に変換して出力

toString() は「数値を文字列に変換するメソッド」

たとえば:

const num = 123;
console.log(num.toString()); // "123"(文字列になる)



実は、toString(基数) って書くと「基数(進数)」を指定できるのがポイント!

つまり:

const num = 10;
console.log(num.toString(2)); // "1010"(2進数の文字列)
0
0
0

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