convert a number from base 10 to base 2 in javascript

To convert a number from base 10 to base 2 in javascript, we can use the bitwise shift operator >> to extract the binary digits from the number. Here's an algorithm to perform the conversion:

  1. Create an empty array to hold the binary digits
  2. While the input number is greater than zero:
    1. Use the bitwise AND operator & with 1 to extract the rightmost binary digit
    2. Push the digit onto the array
    3. Use the bitwise shift operator >> to shift the input number one bit to the right
  3. Join the binary digits in reverse order to form the binary representation of the number

Here's the code implementation of this algorithm in JavaScript:

index.tsx
function decimalToBinary(decimal) {
  let binaryDigits = [];

  while (decimal > 0) {
    const binaryDigit = decimal & 1; // extract rightmost binary digit
    binaryDigits.push(binaryDigit); // add to array of binary digits
    decimal = decimal >> 1; // shift number right by one bit
  }

  return binaryDigits.reverse().join(""); // join digits and return as string
}
372 chars
12 lines

Example usage:

index.tsx
const decimalNumber = 42;
const binaryNumber = decimalToBinary(decimalNumber); // "101010"
console.log(binaryNumber);
118 chars
4 lines

gistlibby LogSnag