2

I have point binary, for example 0.10010011
How to convert it to decimal float?
(0.10010011 = 0.57421875)

var a = 0.10010011
var b = point_bin2dec(a)
console.log(b) // 0.57421875
ramazan793
  • 669
  • 1
  • 9
  • 23

3 Answers3

0

Try this implementation of parseFloat that takes a radix as a second argument.

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
Luiz Chagas Jr
  • 149
  • 1
  • 7
0

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

Claytronicon
  • 1,437
  • 13
  • 14
0

I have point binary, for example 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:

0.100100112 = 100100112/1000000002 = (147/256)10 = 0.57421875

Translated to 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. 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)
}
Tomas Langkaas
  • 4,551
  • 2
  • 19
  • 34