Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert decimal to binary in JS?

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?

like image 858
Sharikov Vladislav Avatar asked Sep 30 '14 18:09

Sharikov Vladislav


People also ask

How do I convert decimal to binary?

Take decimal number as dividend. Divide this number by 2 (2 is base of binary so divisor here). Store the remainder in an array (it will be either 0 or 1 because of divisor 2). Repeat the above two steps until the number is greater than zero.

How do you convert decimal to binary in node JS?

The parseInt() method is used to convert a string value to an integer. The JavaScript built-in method toString([radix]) returns a string value in a specified radix (base). Here, toString(2) converts the decimal number to binary number.

How do you write binary in JavaScript?

Use the string "b" to write a binary file. Use the string "ba" to append to a binary file. Use the string "a" to append to a text file. Use any other string or omit the parameter to write to a text file.

Does JavaScript use binary code?

JavaScript Uses 32 bits Bitwise Operands JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.


3 Answers

let decimal = prompt('please insert decimal number');
console.log(Number(decimal).toString(2));
like image 123
majid Avatar answered Oct 09 '22 17:10

majid


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

like image 20
Eudes Serpa Avatar answered Oct 09 '22 15:10

Eudes Serpa


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));
like image 2
Gepser Hoil Avatar answered Oct 09 '22 15:10

Gepser Hoil