1
0

_pack-ieee754.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Credit: https://github.com/paulmillr/es6-shim/
  2. 'use strict';
  3. var abs = Math.abs, floor = Math.floor, log = Math.log, min = Math.min
  4. , pow = Math.pow, LN2 = Math.LN2
  5. , roundToEven;
  6. roundToEven = function (n) {
  7. var w = floor(n), f = n - w;
  8. if (f < 0.5) return w;
  9. if (f > 0.5) return w + 1;
  10. return w % 2 ? w + 1 : w;
  11. };
  12. module.exports = function (v, ebits, fbits) {
  13. var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes;
  14. // Compute sign, exponent, fraction
  15. if (isNaN(v)) {
  16. // NaN
  17. // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
  18. e = (1 << ebits) - 1;
  19. f = pow(2, fbits - 1);
  20. s = 0;
  21. } else if (v === Infinity || v === -Infinity) {
  22. e = (1 << ebits) - 1;
  23. f = 0;
  24. s = (v < 0) ? 1 : 0;
  25. } else if (v === 0) {
  26. e = 0;
  27. f = 0;
  28. s = (1 / v === -Infinity) ? 1 : 0;
  29. } else {
  30. s = v < 0;
  31. v = abs(v);
  32. if (v >= pow(2, 1 - bias)) {
  33. e = min(floor(log(v) / LN2), 1023);
  34. f = roundToEven(v / pow(2, e) * pow(2, fbits));
  35. if (f / pow(2, fbits) >= 2) {
  36. e = e + 1;
  37. f = 1;
  38. }
  39. if (e > bias) {
  40. // Overflow
  41. e = (1 << ebits) - 1;
  42. f = 0;
  43. } else {
  44. // Normal
  45. e = e + bias;
  46. f = f - pow(2, fbits);
  47. }
  48. } else {
  49. // Subnormal
  50. e = 0;
  51. f = roundToEven(v / pow(2, 1 - bias - fbits));
  52. }
  53. }
  54. // Pack sign, exponent, fraction
  55. bits = [];
  56. for (i = fbits; i; i -= 1) {
  57. bits.push(f % 2 ? 1 : 0);
  58. f = floor(f / 2);
  59. }
  60. for (i = ebits; i; i -= 1) {
  61. bits.push(e % 2 ? 1 : 0);
  62. e = floor(e / 2);
  63. }
  64. bits.push(s ? 1 : 0);
  65. bits.reverse();
  66. str = bits.join('');
  67. // Bits to bytes
  68. bytes = [];
  69. while (str.length) {
  70. bytes.push(parseInt(str.substring(0, 8), 2));
  71. str = str.substring(8);
  72. }
  73. return bytes;
  74. };