简体   繁体   English

将点二进制转换为浮点数

[英]Convert point binary to float

I have point binary, for example 0.10010011我有点二进制,例如 0.10010011
How to convert it to decimal float?如何将其转换为十进制浮点数?
(0.10010011 = 0.57421875) (0.10010011 = 0.57421875)

var a = 0.10010011
var b = point_bin2dec(a)
console.log(b) // 0.57421875

Try this implementation of parseFloat that takes a radix as a second argument.试试这个将基数作为第二个参数的 parseFloat 实现。

const parseFloat = function parseFloat (string, radix = 10) {
  if (radix == 10) {
    return this(string)
  }

  string = String(string);

  const [iString, fString = '0'] = string.split('.')
  const iNumber = parseInt(iString, radix)
  const fNumber = parseInt(fString, radix)
  const fLength = Math.max(fNumber.toString(radix).length, fString.length)
  const sign = Infinity / iNumber === Infinity ? 1 : -1

  return iNumber + sign * fNumber / radix ** fLength
}.bind(parseFloat)

Usage:用法:

parseFloat(0.10010011, 2); // 0.57421875

 function point_bin2dec(num) { var parts = num.toString().split('.'); return parseInt(parts[0], 2) + (parts[1] || '').split('').reduceRight(function (r, a) { return (r + parseInt(a, 2)) / 2; }, 0); } document.write(point_bin2dec(0.10010011));

Modified from an answer to this question How to convert binary fraction to decimal修改自此问题的答案How to convert binary fraction to decimal

I have point binary, for example 0.10010011.我有点二进制,例如 0.10010011。 How to convert it to decimal float?如何将其转换为十进制浮点数?

The easiest and most direct way of doing this conversion in JavaScript, is to represent the floating-point binary as a binary fraction, convert it to a decimal fraction, then compute the floating-point decimal:在 JavaScript 中进行这种转换的最简单和最直接的方法是将浮点二进制表示为二进制分数,将其转换为十进制分数,然后计算浮点十进制:

0.10010011 2 = 10010011 2 /100000000 2 = (147/256) 10 = 0.57421875 0.10010011 2 = 10010011 2 /100000000 2 = (147/256) 10 = 0.57421875

Translated to JavaScript:翻译成 JavaScript:

 a = '0.10010011' b = parseInt(a.replace('.', ''), 2) / (1 << (a.split('.')[1] || '').length); console.log(b); // 0.57421875

We can easily adapt the conversion code to a generic function for parsing floating-points from any base.我们可以轻松地将转换代码改编为通用函数,用于从任何基数解析浮点数。 This stackowerflow answer provides more detail.此 stackowerflow 答案提供了更多详细信息。 Demo code below.演示代码如下。

 var a = '0.10010011'; var b = parseFloatRadix(a, 2); console.log(b); // 0.57421875 function parseFloatRadix(num, radix) { return parseInt(num.replace('.', ''), radix) / Math.pow(radix, (num.split('.')[1] || '').length) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM