21

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?

3
  • This has to be a dup, but binary = int.toString(2);. Commented Sep 30, 2014 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 Commented Sep 30, 2014 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. The accepted answer is not worth of much, but Annan's anwer seems to be what you're looking for. Commented Sep 30, 2014 at 18:25

7 Answers 7

33

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
7

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

1 Comment

Links and code are not enough. You need to explain the answer in your words.
4

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.

1 Comment

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
2

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

2 Comments

Please explain.
Like the other comment that I put in another answer in this thread. You need to indicate why and how is your answer is best suited for OP.
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));

Comments

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

Comments

0

Look at the following code:

function decimalToBinary(number) { return Number(number).toString(2); } decimalToBinary(456565); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.