index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  2. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  3. var e, m
  4. var eLen = (nBytes * 8) - mLen - 1
  5. var eMax = (1 << eLen) - 1
  6. var eBias = eMax >> 1
  7. var nBits = -7
  8. var i = isLE ? (nBytes - 1) : 0
  9. var d = isLE ? -1 : 1
  10. var s = buffer[offset + i]
  11. i += d
  12. e = s & ((1 << (-nBits)) - 1)
  13. s >>= (-nBits)
  14. nBits += eLen
  15. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  16. m = e & ((1 << (-nBits)) - 1)
  17. e >>= (-nBits)
  18. nBits += mLen
  19. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  20. if (e === 0) {
  21. e = 1 - eBias
  22. } else if (e === eMax) {
  23. return m ? NaN : ((s ? -1 : 1) * Infinity)
  24. } else {
  25. m = m + Math.pow(2, mLen)
  26. e = e - eBias
  27. }
  28. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  29. }
  30. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  31. var e, m, c
  32. var eLen = (nBytes * 8) - mLen - 1
  33. var eMax = (1 << eLen) - 1
  34. var eBias = eMax >> 1
  35. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  36. var i = isLE ? 0 : (nBytes - 1)
  37. var d = isLE ? 1 : -1
  38. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  39. value = Math.abs(value)
  40. if (isNaN(value) || value === Infinity) {
  41. m = isNaN(value) ? 1 : 0
  42. e = eMax
  43. } else {
  44. e = Math.floor(Math.log(value) / Math.LN2)
  45. if (value * (c = Math.pow(2, -e)) < 1) {
  46. e--
  47. c *= 2
  48. }
  49. if (e + eBias >= 1) {
  50. value += rt / c
  51. } else {
  52. value += rt * Math.pow(2, 1 - eBias)
  53. }
  54. if (value * c >= 2) {
  55. e++
  56. c /= 2
  57. }
  58. if (e + eBias >= eMax) {
  59. m = 0
  60. e = eMax
  61. } else if (e + eBias >= 1) {
  62. m = ((value * c) - 1) * Math.pow(2, mLen)
  63. e = e + eBias
  64. } else {
  65. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  66. e = 0
  67. }
  68. }
  69. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  70. e = (e << mLen) | m
  71. eLen += mLen
  72. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  73. buffer[offset + i - d] |= s * 128
  74. }