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