Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day389:实现二进制与十进制的互相转化的两个函数? #392

Open
qappleh opened this issue Sep 2, 2021 · 1 comment
Open

Comments

@qappleh
Copy link
Owner

qappleh commented Sep 2, 2021

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Sep 6, 2021

function integerToBin (num) {
  // 64
  const result = []
  while (num / 2) {
    next = num % 2
    num = Math.floor(num / 2)
    result.unshift(next)
  }
  return result
}

function fractionalToBin (num) {
  const result = []
  let i = 0
  while (num !== 0 && i < 54) {
    num = num * 2
    
    next = num >= 1 ? 1 : 0
    num = num % 1
    i++
    result.push(next)
  }
  return result
}

function decToBinary (num) {
  // 1.5
  const [int, fraction] = String(num).split(/(?=\.)/).map((x, i) => {
    return i === 0 ? integerToBin(x) : fractionalToBin(x)
  })
  return [int, fraction]
}

function binToDec (num) {
  const [_int, _fraction] = String(num).split('.')
  const int = _int.split('').reduceRight((acc, x, i) => {
    return acc + x * 2 ** i
  }, 0)
  const fraction = _fraction ? _fraction.split('').reduce((acc, x, i) => {
    return acc + x * 2 ** -(i + 1)
  }, 0) : 0
  return `${int}${fraction ? '.' + fraction.toString().slice(2) : ''}`
}

console.log(16, integerToBin(16), Number(16).toString(2))
console.log(18, integerToBin(18), Number(18).toString(2))
console.log(0.5, fractionalToBin(0.5), Number(0.5).toString(2))
console.log(0.1, fractionalToBin(0.1), Number(0.1).toString(2))
console.log(1.1, decToBinary(1.1), Number(1.1).toString(2))

console.log(7.875, decToBinary(7.875), Number(7.875).toString(2))
console.log('111.111', binToDec('111.111'), parseInt('111.111', 2))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant