Converting a decimal to binary
Saturday, Jan 18, 2020
JavaScript
JavaScript
I wrote this simple function in JavaScript to convert a decimal to binary. Remainder of dividing the number by 2 is pushed to an array. At the end the array is reversed and the elements joined together.
// dec2bin.js -- converts a decimal integer to a binary number
function dec2bin(n)
{
if (!Number.isInteger(n))
{
console.log(n, "is not an integer");
return null;
}
s = [];
while ((n - n % 2)/2 > 0)
{
s.push(n % 2);
n = (n - n % 2) / 2;
}
s.push(n);
return s.reverse().join("");
}
// let's test it
console.log(dec2bin(19));
console.log(dec2bin(215654));
console.log(dec2bin(4.5));
10011
110100101001100110
4.5 is not an integer
null