JS中如何将十进制转换为二进制?

问题描述 投票:0回答:6

可以通过以下方式将二进制转换为十进制:

var binary = "110";
var int = parseInt(binary, 2);
document.getElementById("results").innerHTML = int;
<div id="results"></div>

但是,我如何做相反的操作:将 int 转换为二进制?

javascript binary decimal converters
6个回答
27
投票

let decimal = prompt('please insert decimal number');
console.log(Number(decimal).toString(2));


5
投票

Dec 到 Bin:原始(按位)

/**
*   Dec to Bin 
*   with bitwise operations
*
*   Eudes Serpa M.
**/

const numberToConvert = 5;
const numberOfBits = 32; // 32-bits binary
const arrBitwise = [0]; // save the resulting bitwise

for (let i=0; i<numberOfBits; i++) {
    let mask = 1;

    const bit = numberToConvert & (mask << i); // And bitwise with left shift

    if(bit === 0) {
        arrBitwise[i] = 0;
    } else {
        arrBitwise[i] = 1;
    }
}

const binary = arrBitwise.reverse().join("");

console.log(`This is the resulting binary: ${binary}`)
console.log(`This is the verification ${parseInt(binary, 2)}`);

说明:

  • 第 2 行:我们指定组成生成的二进制文件的位数。

  • 第 3 行:我们定义一个数组,用于保存位级操作产生的位。最后,这将是我们生成的二进制文件(反转它)

  • For:用于“创建”二进制位。

  • 掩码:表示我们在位级别移位到的数字(1 进行 AND 运算并获得要转换的数字 1 中的位)。

  • bit:执行运算的结果位,例如:

    位数 = 3;

    掩码= 1;

    for (i = 0 -> 31) { // 32 位

      // Explanation of the operation to obtain the bit in position i
    
      // ---- For i = 0;
      1. mask << 0 = ...0001 (a 1 in decimal), since it does not do any shifting.
    
      2. 3 & 1
          /* At the bit level we have to
               3 = ...0011
               1 = ...0001,
               so when doing the AND operation at the bit level, we have to:
           0011
          &0001
          ------
          0001 === 1 decimal
       */
    
      // bit then takes the value resulting from the previous operations. This is: 
      bit = 1;
    
      // The if is not meet, so it enters the else:
      arrBitwise[0] = 1;
    
      // ---- For i = 1;
      1. mask << 1 = ...0010 (a 2 in decimal)
    
      2. 3 & 2
          /* At the bit level we have to
               3 = ...0011
               2 = ...0010,
               so when doing the AND operation at the bit level, we have to:
          0011
         &0010
         -------
          0010 === 2 decimal
       */
    
      // bit then takes the value resulting from the previous operations. This is: bit = 2;
    
      // The if is not meet, so it enters the else:
      arrBitwise[1] = 1;
    
    
      // ----- For i = 2;
      1. mask << 2 = ...0100 (a 4 in decimal)
    
      2. 3. 4
          /* At the bit level we have to
               3 = ...0011
               4 = ...0100,
               so when doing the AND operation at the bit level, we have to:
          0011
         &0100
        -------
          0000 === 0 decimal
       */
    
      // bit then takes the value resulting from the previous operations. This is: 
      bit = 0;
    
     // The if meet, so:
      arrBitwise[2] = 0;
    

    }

因此,arrBitwise 将是: arr按位 = [1, 1, 0, 0, ..., 0];

arrBitwise.reverse() // [0, ..., 0, 0, 1, 1]

与.join()

"0...0011"

用二进制表示3。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift


2
投票

二进制和十进制都是具有不同基数的数字的字符串表示形式。

这就是为什么我们在从字符串获取数字时需要指定基数:

binary = '10101'
decimal = '21'
Number.parseInt(binary, 2) === Number.parseInt(decimal, 10) // true

同样,当我们将数字转换为字符串时,我们可以(但不必)指定基数:

n = 21
n.toString(2) // '10101'

Radix 在这里是可选的,省略时等于 10:

n = 21
n.toString() // '21'

请参阅 Number.prototype.toString() 了解更多详细信息。


2
投票

您可以尝试使用无符号右移运算符

>>> 0
运算符对数字没有影响,但会给出二进制等价值。

您可以运行下面的代码片段(如果尝试使用-6,输出应为 11111111111111111111111111111010)。

//Here you can test it directly
var number = -6;

alert((number >>> 0).toString(2));

//Or you can do it with a function
function dec2Bin(dec) {
  return (dec >>> 0).toString(2);
}

alert(dec2Bin(-6));


1
投票

var x = 6;
console.log(x.toString(2));


1
投票

代码在注释中有解释

const input = 18;
const converted = deciToBinary(18, '') // function to convert decimal to binary
const countOnes = countOne(converted); // function to count the occurence of 1s

console.log(countOnes);
function countOne(input) {
    const strlen = input.length;
    let count = 0;
    for (let i = 0; i < strlen; i++) {
        if (parseInt(input[i])) {
            count++
        }
    }
    return count;
}



function deciToBinary(input, output) {
    const reminder = input % 2; // find the reminder
    const quotient = parseInt(input / 2); // find the quotient
    if (quotient > 1) { // if quotient is > 1 i.e not 0 or 1
        output += reminder; // add the reminder to the string
        return deciToBinary(quotient, output); // using recursive function concept, recall the function
    }
    output += reminder; // add the reminder
    output += quotient; // add the quotient
    const binary = output.split('').reverse().join(''); // reverse the string
    return binary;
}

© www.soinside.com 2019 - 2024. All rights reserved.