convert a number from base 10 to base 8 in typescript

To convert a number from base 10 to base 8, we need to divide the number successively by 8 until the quotient becomes 0. The remainders will be collected in reverse order to obtain the base 8 number.

Here's a TypeScript function that implements this algorithm:

index.ts
function base10ToBase8(n: number): number {
  let result = '';
  while (n > 0) {
    result = (n % 8) + result;
    n = Math.floor(n / 8);
  }
  return parseInt(result, 8);
}
175 chars
9 lines

The function takes a number n in base 10 and returns the corresponding number in base 8. The remainders are collected in the string result, which is then parsed as a base 8 number using the parseInt function.

Here's how to use the function:

index.ts
const decimalNumber = 123;
const octalNumber = base10ToBase8(decimalNumber);
console.log(octalNumber); // Output: 173
118 chars
4 lines

In this example, we convert the decimal number 123 to its equivalent in base 8, which is 173.

gistlibby LogSnag