Skip to content

二进制转八进制

二进制转八进制

代码

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

import { binaryToDecimal } from "../binaryToDecimal/javascript"

export function binaryToOctal (binary) {
  let octal = ''
  for (let i = binary.length - 1; i > -1; i-=3) {
    const start = i - 2
    octal = binaryToDecimal(binary.slice(start < 0 ? 0 : start, i + 1)) + octal
  }
  return octal
}
typescript
// 二进制转八进制
// 输入:'1101'
// 输出:'15'

import { binaryToDecimal } from "../binaryToDecimal/typescript"

export function binaryToOctal (binary: string): string {
  let octal = ''
  for (let i = binary.length - 1; i > -1; i-=3) {
    const start = i - 2
    octal = binaryToDecimal(binary.slice(start < 0 ? 0 : start, i + 1)) + octal
  }
  return octal
}

测试代码

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

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

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

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

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