17

It is possible to convert binary to decimal by this:

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

But, how I can do an opposite operation: converting int to binary?

Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
  • This has to be a dup, but `binary = int.toString(2);`. – Teemu Sep 30 '14 at 18:12
  • Forget to say. I also to convert negative numbers. Method, you suggested give "-110" as result, when I try to convert -6 to binary – Sharikov Vladislav Sep 30 '14 at 18:15
  • 1
    Well, it's not perfect, you'd have to know the byte length when converting negative values. [Here's a dup](http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript). The accepted answer is not worth of much, but [Annan's anwer](http://stackoverflow.com/a/24153275/1169519V) seems to be what you're looking for. – Teemu Sep 30 '14 at 18:25

6 Answers6

27

let decimal = prompt('please insert decimal number');
console.log(Number(decimal).toString(2));
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
majid
  • 404
  • 4
  • 8
  • While your answer could be a possible solution to solve the OP problem, you need to indicate why and how is your answer is best suited for OP. – SMAKSS Aug 01 '20 at 06:55
  • 1
    Note that this answer doesn't correctly convert negative decimal numbers to binary as represented in memory. If that's important to you see @Gepser Hoil's answer. – Slavi May 18 '22 at 17:31
5

Dec to Bin: raw (bitwise)

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

Explanation:

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

    }

And so, arrBitwise would then be: arrBitwise = [1, 1, 0, 0, ..., 0];

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

with .join()

"0...0011"

Which represents 3 in binary.

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

Eudes Serpa
  • 114
  • 1
  • 5
2

You can try with the Unsigned Right Shift Operator.

The >>> 0 operator has no effect in the number but give you the binary equivalent.

You can run the code snippet below (the output should be 11111111111111111111111111111010 if try it with -6).

//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));
Gepser Hoil
  • 3,998
  • 4
  • 24
  • 34
2

Both binary and decimal are string representations of a number with different radix.

That's the reason why we need to specify the radix when getting a number from a string:

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

Likewise, when we convert a number to a string, we can (but doesn't have to) specify the radix:

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

Radix is optional here and equals 10 when omitted:

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

See Number.prototype.toString() for more details.

enkryptor
  • 1,574
  • 1
  • 17
  • 27
  • 1
    I understand all this, and its exactly what i wanted. Just thank you so much for the nice explanation. learned a new word today radix – Gauthier Apr 27 '22 at 15:56
1

var x = 6;
console.log(x.toString(2));
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
Darius
  • 137
  • 1
  • 3
1

The code is explained in comments

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;
}
Alaksandar Jesus Gene
  • 6,523
  • 12
  • 52
  • 83