12345678910111213141516171819202122232425262728293031323334
  1. /* eslint no-bitwise: "off" */
  2. // Credit: https://github.com/paulmillr/es6-shim/
  3. "use strict";
  4. var pow = Math.pow;
  5. module.exports = function (bytes, ebits, fbits) {
  6. // Bytes to bits
  7. var bits = [], i, j, bit, str, bias, sign, e, fraction;
  8. for (i = bytes.length; i; i -= 1) {
  9. bit = bytes[i - 1];
  10. for (j = 8; j; j -= 1) {
  11. bits.push(bit % 2 ? 1 : 0);
  12. bit >>= 1;
  13. }
  14. }
  15. bits.reverse();
  16. str = bits.join("");
  17. // Unpack sign, exponent, fraction
  18. bias = (1 << (ebits - 1)) - 1;
  19. sign = parseInt(str.substring(0, 1), 2) ? -1 : 1;
  20. e = parseInt(str.substring(1, 1 + ebits), 2);
  21. fraction = parseInt(str.substring(1 + ebits), 2);
  22. // Produce number
  23. if (e === (1 << ebits) - 1) return fraction === 0 ? sign * Infinity : NaN;
  24. if (e > 0) return sign * pow(2, e - bias) * (1 + fraction / pow(2, fbits));
  25. if (fraction !== 0) return sign * pow(2, -(bias - 1)) * (fraction / pow(2, fbits));
  26. return sign < 0 ? -0 : 0;
  27. };