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

18

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

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

但是,我该如何执行相反的操作:将整数转换为二进制?


这可能是一个重复的问题,但是 binary = int.toString(2); - Teemu
忘了说,我也需要转换负数。你建议的方法在我尝试将-6转换为二进制时会给出“-110”作为结果。 - Sharikov Vladislav
1
嗯,它并不完美,当转换负值时,你必须知道字节长度。这里有一个重复的问题。被接受的答案并不是很有价值,但是Annan的回答似乎是你要找的。 - Teemu
6个回答

27

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


虽然您的回答可能是解决 OP 问题的可能解决方案,但您需要说明为什么以及如何使您的答案最适合 OP。 - SMAKSS
1
请注意,此答案未正确将负十进制数转换为内存中的二进制表示。如果这对您很重要,请参阅@Gepser Hoil的答案。 - Slavi

6

十进制转二进制:原始(按位)

/**
*   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)}`);

说明:

  • Line 2: We specify the number of bits that will make up the resulting binary.

  • Line 3: We define an array in which we are going to save the bit resulting from the bit-level operations. In the end, it will be our resulting binary (reversing it)

  • For: Used to "create" the binary of bits.

  • Mask: Indicates the number to which we shift at the bit level (a 1 to do the AND and obtain the bits in 1 of the number to convert).

  • bit: It is the resulting bit of performing the operation, for example:

    numberOfBits = 3;

    mask = 1;

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

      // 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将是: arrBitwise = [1、1、0、0、...、0];
arrBitwise.reverse() // [0, ..., 0, 0, 1, 1]

使用.join()方法

"0...0011"

二进制中表示数字3的方式是什么。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Bitwise_AND

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Left_shift


链接和代码并不足够。您需要用自己的话解释答案。 - Amit

2

二进制和十进制都是数字的字符串表示,只是使用不同的进制。因此,在从字符串中获取数字时,我们需要指定其进制。

这就是为什么我们需要在从字符串 获取数字时指定进制的原因:

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

同样地,当我们将一个数字转换成字符串时,我们可以(但不必)指定基数:
n = 21
n.toString(2) // '10101'

当省略时,此处的基数是可选的,默认为10:

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

详见Number.prototype.toString()获取更多详细信息。


1
我理解了所有的内容,这正是我想要的。非常感谢您详细的解释,今天我学到了一个新词"radix"。 - Gauthier

2

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


4
请解释。 - Stephan-v
4
就像我在另一个回答中提到的评论一样,您需要说明为什么和如何您的答案最适合楼主。 - SMAKSS

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

这段代码在注释中有详细的解释。

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;
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接