Skip to content

八进制转二进制

八进制转二进制

代码

javascript
// 八进制转二进制
// 输入:'15'
// 输出:'1101'

import { decimalToBinary } from "../decimalToBinary/javascript"
import { leftFillZero } from "../../utilsJs"

export function octalToBinary (octal) {
  let res = ''
  for (let i = 0; i < octal.length; i++) {
    const nowStr = decimalToBinary(Number(octal[i]))
    res += i > 0 ? leftFillZero(nowStr, 3) : nowStr
  }
  return res
}
typescript
// 八进制转二进制
// 输入:'15'
// 输出:'1101'

import { decimalToBinary } from "../decimalToBinary/typescript"
import { leftFillZero } from "../../utils"

export function octalToBinary (octal: string): string {
  let res = ''
  for (let i = 0; i < octal.length; i++) {
    const nowStr = decimalToBinary(Number(octal[i]))
    res += i > 0 ? leftFillZero(nowStr, 3) : nowStr
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { octalToBinary } from './typescript.ts'
import { octalToBinary as octalToBinaryJs } from './javascript.js'

test(`'15' to '1101'`, () => {
  expect(octalToBinary('15')).toBe('1101')
})

test(`'15' to '1101'`, () => {
  expect(octalToBinaryJs('15')).toBe('1101')
})

test(`'11' to '1001'`, () => {
  expect(octalToBinary('11')).toBe('1001')
})

test(`'11' to '1001'`, () => {
  expect(octalToBinaryJs('11')).toBe('1001')
})