convert a number from base 2 to base 8 in typescript

To convert a number from base 2 to base 8 in TypeScript, you can follow these steps:

  1. Convert the binary number to decimal.
  2. Convert the decimal number to octal.

Here's the code:

index.ts
function base2ToBase8(binaryNum: string): string {
  // Step 1: Convert binary to decimal
  const decimalNum = parseInt(binaryNum, 2);

  // Step 2: Convert decimal to octal
  const octalNum = decimalNum.toString(8);

  return octalNum;
}
239 chars
10 lines

This function takes in a binary number as a string and returns the equivalent octal number as a string.

For example, calling base2ToBase8('10101110') will return '256'.

gistlibby LogSnag