10進数を2進数に変換するJavaScriptプログラム

Javascript

例1:10進数を2進数に変換する

// program to convert decimal to binary
function convertToBinary(x) {
    let bin = 0;
    let rem, i = 1, step = 1;
    while (x != 0) {
        rem = x % 2;
        console.log(
            `Step ${step++}: ${x}/2, Remainder = ${rem}, Quotient = ${parseInt(x/2)}`
        );
        x = parseInt(x / 2);
        bin = bin + rem * i;
        i = i * 10;
    }
    console.log(`Binary: ${bin}`);
}

// take input
let number = prompt('Enter a decimal number: ');

convertToBinary(number);

出力

Step 1: 9/2, Remainder = 1, Quotient = 4
Step 2: 4/2, Remainder = 0, Quotient = 2
Step 3: 2/2, Remainder = 0, Quotient = 1
Step 4: 1/2, Remainder = 1, Quotient = 0
Binary: 1001

上記のプログラムでは、ユーザーは10進数を入力するように求められます。 ユーザーが入力した番号は、引数として convertToBinary() 関数。

ザ・ while ループは、ユーザーが入力した番号が次のようになるまで使用されます 0

バイナリ値は次のように計算されます。

bin = bin + rem * i;

ここに、 rem はモジュラスです % で割ったときの数値 2 そして 2進数の場所の値を示します。


例2:toString()を使用して10進数を2進数に変換する

// program to convert decimal to binary

// take input
const number = parseInt(prompt('Enter a decimal number: '));

// convert to binary
const result = number.toString(2);

console.log('Binary:' + ' ' + result);

出力

Enter a decimal number: 9
Binary: 1001

上記のプログラムでは、ユーザーは番号を入力するように求められます。 ザ・ parseInt() メソッドは、文字列値を整数に変換するために使用されます。

JavaScript組み込みメソッド toString([radix]) 指定された基数(基数)の文字列値を返します。 ここに、 toString(2) 10進数を2進数に変換します。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です