Skip to content

十六进制转二进制

十六进制转二进制

代码

javascript
// 十六进制转二进制
// 输入:'16'
// 输出:'10110'

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

export function hexadecimalToBinary (hex) {
  let res = ''
  hex = hex.toLowerCase()
  const strToNumber = {
    a: '10',
    b: '11',
    c: '12',
    d: '13',
    e: '14',
    f: '15'
  }
  for (let i = 0; i < hex.length; i++) {
    let nowStr = hex[i]
    nowStr = strToNumber[nowStr] ? strToNumber[nowStr] : nowStr
    const curStr = decimalToBinary(Number(nowStr))
    res += i > 0 ? leftFillZero(curStr, 4) : curStr
  }
  return res
}
typescript
// 十六进制转二进制
// 输入:'16'
// 输出:'10110'

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

export function hexadecimalToBinary (hex: string): string {
  let res = ''
  hex = hex.toLowerCase()
  const strToNumber: { [key: string]: string } = {
    a: '10',
    b: '11',
    c: '12',
    d: '13',
    e: '14',
    f: '15'
  }
  for (let i = 0; i < hex.length; i++) {
    let nowStr = hex[i]
    nowStr = strToNumber[nowStr] ? strToNumber[nowStr] : nowStr
    const curStr = decimalToBinary(Number(nowStr))
    res += i > 0 ? leftFillZero(curStr, 4) : curStr
  }
  return res
}

测试代码

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

test(`hexadecimalToBinary 16`, () => {
  expect(hexadecimalToBinary('16')).toBe('10110')
})

test(`hexadecimalToBinaryJs 16`, () => {
  expect(hexadecimalToBinaryJs('16')).toBe('10110')
})

test(`hexadecimalToBinary 1b`, () => {
  expect(hexadecimalToBinary('1b')).toBe('11011')
})

test(`hexadecimalToBinaryJs 1b`, () => {
  expect(hexadecimalToBinaryJs('1b')).toBe('11011')
})

test(`hexadecimalToBinary 1F`, () => {
  expect(hexadecimalToBinary('1F')).toBe('11111')
})

test(`hexadecimalToBinaryJs 1F`, () => {
  expect(hexadecimalToBinaryJs('1F')).toBe('11111')
})