1
0

_unpack-ieee754.js 832 B

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