'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?
Solution 1:[1]
let decimal = prompt('please insert decimal number');
console.log(Number(decimal).toString(2));
Solution 2:[2]
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
Solution 3:[3]
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.
Solution 4:[4]
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));
Solution 5:[5]
var x = 6;
console.log(x.toString(2));
Solution 6:[6]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SMAKSS |
| Solution 2 | |
| Solution 3 | enkryptor |
| Solution 4 | |
| Solution 5 | SMAKSS |
| Solution 6 | Alaksandar Jesus Gene |
