shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 508 forks source link

【Q663】给定一个数值,给出它在 IEEE754 的表示,如符号位、指数位与分数位 #681

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

相关问题:

shfshanyue commented 3 years ago

代码见: 给定一个数值,给出它在 IEEE754 的表示,如符号位、指数位与分数位 - codepen

function formatToBinaryExponent (num) {
  const [int, dec] = String(num).split(/(?=\.)/).map(x => Number(x).toString(2))
  const exponent = (int.length - 1).toString(2)
  const fraction = int.slice(1) + dec.slice(2)
  return {
    exponent,
    fraction: fraction.slice(0, 52),
    sign: num > 0,
    exact: fraction.length < 52,
  }
}

console.log(formatToBinaryExponent(13.5))