Onjsdev

Share


Convert decimals to binary

Convert Decimals To Binary In Javascript


By onjsdev

Nov 11th, 2023

Binary code is an essential component of computer science, and it is frequently necessary to convert decimal or hexadecimal values to binary. This article will explore the implementation of this conversion process using both recursive and iterative functions in javascript.

Convert Decimals Iteratively to Other Bases

We will develop a function that can perform conversions not just from decimal to binary, but also from decimal to other base values. Let's see.

function convert(number, base) {
  let output = '';
  while (number >= base) {
    const result = Math.floor(number / base);
    const remainder = number % base;
    output = `${remainder + output}`;
    number = result;
  }
  return `${number + output}`;
}

console.log(convert(13, 2)); //1101

Convert Decimals Recursively to Other Bases

We can obtain the result by continuously dividing the given number by the given base, and this process can also be achieved by implementing a recursive function.

function convert(number, base, output = '') {
  if (number < base) {
    output = `${number + output}`;
    return output;
  }
  const result = Math.floor(number / base);
  const remainder = number % base;
  output = `${remainder + output}`;
  return convert(result, base, output);

Conclusion

To summarize, this article has demonstrated how to perform conversions from decimal to binary in JavaScript, utilizing both the iterative and recursive methods.

Thank you for reading.